0

I developed a system that requires the user to login. I am using Android Studio (JAVA) to code the apps and PHP to connect from apps to a MySQL database. Before the error happened, I used MySQLi method and it worked. But when I converted it to PDO, I got some error. When I see the logcat at android studio, the error states:

1) Value br of type java.lang.String cannot be converted to JSONObject

Below is my code:

MainActivity.JAVA

        public class MainActivity extends AppCompatActivity {

        EditText etBadgeid, etPassword;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            etBadgeid = findViewById(R.id.etBadgeid);
            etPassword = findViewById(R.id.etPassword);

            findViewById(R.id.btnLogin).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    userLogin();
                }
            });
        }

        private void userLogin() {
            final String badgeid = etBadgeid.getText().toString();
            final String pwd = etPassword.getText().toString();

            class UserLogin extends AsyncTask<Void, Void, String> {

                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                }

                @Override
                protected void onPostExecute(String s) {
                    super.onPostExecute(s);

                    try {
                        //converting response to json object
                        JSONObject obj = new JSONObject(s);

                        //if no error in response
                        if (!obj.getBoolean("error")) {
                            Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();

                            //getting the user from the response
                            JSONObject userJson = obj.getJSONObject("user");

                            //creating a new user object
                            User user = new User(
                                                userJson.getString("badgeid"),
                                                userJson.getString("email"),
                                                userJson.getString("fullname"),
                                                userJson.getInt("roles_id"),
                                                userJson.getInt("team_id")
                            );

                            //storing the user in shared preferences
                            SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);

                            //starting the profile activity
                            finish();
                            startActivity(new Intent(getApplicationContext(), Home.class));
                        } else {
                            Toast.makeText(getApplicationContext(), "Invalid username or password", Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected String doInBackground(Void... voids) {
                    //creating request handler object
                    RequestHandler requestHandler = new RequestHandler();

                    //creating request parameters
                    HashMap<String, String> params = new HashMap<>();
                    params.put("badgeid", badgeid);
                    params.put("pwd", pwd);

                    //returing the response
                    return requestHandler.sendPostRequest(URLs.URL_LOGIN, params);
                }
            }

            UserLogin ul = new UserLogin();
            ul.execute();
        }

        @Override
        public void onBackPressed() {

            finish();
            System.exit(0);
        }
    }

login.php

    <?php 

    require_once 'configPDO.php';

    $response = array();

        if(isTheseParametersAvailable(array('badgeid', 'pwd'))){

            $badgeid = $_POST['badgeid'];
            $pwd = $_POST['pwd']; 

            $stmt = $conn->prepare("SELECT badgeid, email, fullname, roles_id, team_id FROM users WHERE badgeid = :badgeid AND pwd = :pwd AND roles_id = 3");
            // $stmt->bind_param("ss",$badgeid, $pwd);

            $stmt->bindParam(':badgeid',$badgeid,PDO::PARAM_STR);
            $stmt->bindParam(':pwd',$pwd,PDO::PARAM_STR);
            $stmt->execute();

            //$stmt->store_result();

            $result = $stmt->fetch(\PDO::FETCH_ASSOC); // Get results as array
            if ($result) {
                // Since we only get the fields we want to send back, you can assign `$result` directly to `$response['user']`
                $response['user'] = $result; 

                $response['error'] = false; 
                $response['message'] = 'Login successfull'; 
                $response['user'] = $user; 
            }else{
                $response['error'] = false; 
                $response['message'] = 'Invalid username or password';
            }
        }
    echo json_encode($response);

    function isTheseParametersAvailable($params){

        foreach($params as $param){
            if(!isset($_POST[$param])){
                return false; 
            }
        }
        return true; 
    }

?>

Does anyone know what is the problem?

jkdev
  • 11,360
  • 15
  • 54
  • 77
  • This normally mean the return string contains HTML code (usually because PHP throws an error) – catcon Dec 10 '19 at 01:54
  • @catcon thanks for your reply. can you know the code that I need to change? which lines? Really appreciate. – Radamel Falcao Dec 10 '19 at 01:55
  • It seems `JSONObject obj = new JSONObject(s);` may throws this exception, could you know what parameter `s` looks like? – LHCHIN Dec 10 '19 at 01:57
  • @LHCHIN, Sorry, I don't know. I'm just new in android programming. – Radamel Falcao Dec 10 '19 at 01:59
  • Is it the same problem which you have asked before? - [Android Error: Value
    ` in HTML. So you must check the content of response first!
    – LHCHIN Dec 10 '19 at 02:10
  • @LHCHIN.. absolutely, my question before. Can u guide me on how to check the content of response? – Radamel Falcao Dec 10 '19 at 02:28
  • You can either use debug mode in your IDE or just print parameter `s` out in `catch` block. – LHCHIN Dec 10 '19 at 02:45
  • Like @LHCHIN mentioned, just print out the content of `s` in the catch block. Follow the answer in the topic https://stackoverflow.com/questions/16780294/how-to-print-to-the-console-in-android-studio to see how to print messages in console in android. – CodyKL Dec 10 '19 at 03:22
  • what string you are getting as response can you post over here? – Sandeep dhiman Dec 10 '19 at 05:57
  • @Sandeepdhiman Undefined variable: user in C:\xampp\htdocs\otworker\login.php on line 24
    {"user":null,"error":false,"message":"Login successfull"}
    – Radamel Falcao Dec 12 '19 at 03:50

0 Answers0