0

Im developing an application for school which requires a login system. It worked before but I added some new rows in my online database and I also modified the Java code inside my app to store those data, but now when I click the login button nothing is done, it doesnt change activity to my dashboard activity, it doesnt show a message with succesfull login or an error, it doesnt do anything. Here's my Debug console:

W/System.err: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
        at org.json.JSON.typeMismatch(JSON.java:112)
W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:163)
W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:176)
W/System.err:     at quizonwheels.quizonwheels.LoginActivity$3.onResponse(LoginActivity.java:74)
W/System.err:     at quizonwheels.quizonwheels.LoginActivity$3.onResponse(LoginActivity.java:69)
W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:78)
W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:106)
W/System.err:     at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err:     at android.os.Looper.loop(Looper.java:193)
W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
W/System.err:     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

I'm new to Java, our teacher didnt explain us too much and I do not understand why it's not working.

Here's my login function and SharedPrefManager class

private void userLogin(){
        final String username = UsernameEt.getText().toString().trim();
        final String password = PasswordEt.getText().toString().trim();
       progressDialog.show();
        StringRequest stringRequest = new StringRequest(
                Request.Method.POST, Constants.URL_LOGIN, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                progressDialog.dismiss();
                try {
                    JSONObject obj = new JSONObject(response);
                    if (!obj.getBoolean("error")){
                        SharedPrefManager.getInstance(getApplicationContext()).userLogin(
                                obj.getInt("id"),
                                obj.getString("username"),
                                obj.getString("email"),
                                obj.getString("firstname"),
                                obj.getString("lastname"),
                                obj.getString("country"),
                                obj.getString("points")
                        );
                        startActivity(new Intent(getApplicationContext(),DashboardActivity.class));
                        finish();
                    }else
                    {
                        Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
               progressDialog.dismiss();
                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
            }
        }
        ){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> params = new HashMap<>();
                params.put("username",username);
                params.put("password",password);
                return params;
            }
        };

        RequestHandler.getInstance(this).addToRequestQueue(stringRequest);

and my SharedPrefManager class

package quizonwheels.quizonwheels;
import android.content.Context;
import android.content.SharedPreferences;




public class SharedPrefManager {
    private static SharedPrefManager mInstance;

    private static Context mCtx;
    private static final String SHARED_PREF_NAME ="mysharedpref12";
    private static final String KEY_USERNAME="username";
    private static final String KEY_USER_EMAIL="email";
    private static final String KEY_USER_ID="id";
    private static final String KEY_USER_FIRSTNAME="firstname";
    private static final String KEY_USER_LASTNAME="lastname";
    private static final String KEY_USER_COUNTRY="country";
    private static final String KEY_USER_POINTS="points";

    private SharedPrefManager(Context context) {
        mCtx = context;

    }

    public static synchronized SharedPrefManager getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new SharedPrefManager(context);
        }
        return mInstance;
    }

    public boolean userLogin(int id, String username, String email, String firstname, String lastname, String country, String points) {
        SharedPreferences sharedPreferences= mCtx.getSharedPreferences(SHARED_PREF_NAME,Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt(KEY_USER_ID,id);
        editor.putString(KEY_USER_EMAIL,email);
        editor.putString(KEY_USERNAME,username);
        editor.putString(KEY_USER_LASTNAME,lastname);
        editor.putString(KEY_USER_FIRSTNAME,firstname);
        editor.putString(KEY_USER_COUNTRY,country);
        editor.putString(KEY_USER_POINTS,points);

        editor.apply();
        return true;
    }

    public boolean isLoggedIn(){
        SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        if(sharedPreferences.getString(KEY_USERNAME,null)!=null){
            return true;
        }
        return false;
    }

    public boolean logout(){
        SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        editor.apply();
        return true;
    }
}

my php code is:

<?php 

require_once '../includes/DbConnect.php';

$response =array(); 

if($_POST['username'] && $_POST['password']){
    $username = $_POST['username'];
    $password = $_POST['password'];

    $sql = "SELECT * FROM users WHERE username=?";
    $stmt = mysqli_stmt_init($con);
    mysqli_stmt_bind_param($stmt,"s",$username);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    if($user = mysqli_fetch_assoc($result))
    {
        $passwordCheck = password_verify($password,$user['password']);
        if($passwordCheck == false){
            $response['error'] = true; 
            $response['message'] = "Invalid username or password";  
        }
        else if($passwordCheck == true) {

            $response['error'] = false; 
            $response['id'] = $user['idUsers'];
            $response['email'] = $user['email'];
            $response['username'] = $user['username'];
            $response['country']= $user['country'];
             $response['firstname']= $user['firstname'];
              $response['lastname']= $user['lastname'];
               $response['points']= $user['points'];
        }
    }
}



echo json_encode($response);

?>
corner12
  • 33
  • 5

2 Answers2

0

set the breakpoint at this line:

JSONObject obj = new JSONObject(response);

copy the response string value and check if it is a valid JSON string.

Here is a good online JSON validate website.

navylover
  • 12,383
  • 5
  • 28
  • 41
0

Pay attention to this code

 @Override
        public void onResponse(String response) {
            progressDialog.dismiss();
            try {
                JSONObject obj = new JSONObject(response);

Repair "response" to "response.toString()" , enjoy.

@Override
    public void onResponse(String response) {
        progressDialog.dismiss();
        try {
            JSONObject obj = new JSONObject(response.toString());
truong luu
  • 392
  • 1
  • 14
  • i get response as: ' [ ] ' , and if im calling the address where my php code is, it shows ' [] ' . I edited the question with the php code – corner12 Dec 05 '18 at 03:18
  • I do not know anything about php but you can refer to this question: https://stackoverflow.com/questions/19361282/why-would-json-encode-return-an-empty-string – truong luu Dec 05 '18 at 03:26