-2

I know this is a really common topic but I'm getting this error and don't know why. The code is working absolutely fine in Eclipse but crashing on Button click in Studio. The only difference I can think of is Request.Method instead of Method as in Eclipse. Earlier I thought its because, the values from edittext are not getting. But its showing in Toast.

Error

01-13 11:13:34.242 14427-14427/com.sam.sports E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.sam.sports, PID: 14427
java.lang.NullPointerException
at com.sam.sports.LoginPage.checkLogin(LoginPage.java:180)
at com.sam.sports.LoginPage.access$200(LoginPage.java:28)
at com.sam.sports.LoginPage$1.onClick(LoginPage.java:80)
at android.view.View.performClick(View.java:4562)
at android.view.View$PerformClick.run(View.java:18918)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5388)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:655)
at dalvik.system.NativeStart.main(Native Method)
01-13 11:13:38.996 14427-14427/com.sam.sports I/Process: Sending signal. PID: 14427 SIG: 9
public class LoginPage extends AppCompatActivity {
    private static final String TAG = RegisterPage.class.getSimpleName();
    private Button btnLogin;
    private Button btnLinkToRegister;
    private EditText inputEmail;
    private EditText inputPassword;
    private ProgressDialog pDialog;
    private SessionManager session;
    private SQLiteHandler db;

    String name;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loginpage);

        inputEmail = (EditText) findViewById(R.id.email_login);
        inputPassword = (EditText) findViewById(R.id.password_login);
        btnLogin = (Button) findViewById(R.id.login_btn);
        btnLinkToRegister = (Button) findViewById(R.id.btnLinktoRegd);



        // Progress dialog
        pDialog = new ProgressDialog(this);
        pDialog.setCancelable(false);

        // SQLite database handler
        db = new SQLiteHandler(getApplicationContext());

        // Session manager
        session = new SessionManager(getApplicationContext());

        // Check if user is already logged in or not
        if (session.isLoggedIn()) {
            // User is already logged in. Take him to main activity
            Intent intent = new Intent(LoginPage.this, HomePage.class);
            startActivity(intent);
            finish();
        }

        // Login button Click Event
        btnLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                // Check for empty data in the form
                if (!email.isEmpty() && !password.isEmpty()) {
                    // login user
                    checkLogin(email, password);
                    //Toast.makeText(getApplicationContext(), email + "\n" + password, Toast.LENGTH_LONG ).show();
                } else {
                    // Prompt user to enter credentials
                    Toast.makeText(getApplicationContext(), "Please enter the credentials!", Toast.LENGTH_LONG).show();
                }
            }

        });

        // Link to Register Screen
        btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                startActivity(new Intent(LoginPage.this, RegisterPage.class));
                finish();
            }
        });

    }

    /**
     * function to verify login details in mysql db
     * */
    private void checkLogin(final String email, final String password) {
        // Tag used to cancel the request
        String tag_string_req = "req_login";

        pDialog.setMessage("Logging in ...");
        showDialog();

        StringRequest strReq = new StringRequest(Request.Method.POST,
                AppConfig.URL_LOGIN, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Login Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    String status = jObj.getString("status");

                    // Now check status value
                    if (status.equals("0")) {

                        Toast.makeText(getApplicationContext(), "Email or Password may be incorrect! Please try again.", Toast.LENGTH_LONG).show();

                    }else if(status.equals("1")){
                        // user successfully logged in
                        // Create login session
                        session.setLogin(true);

                        // Now store the user in SQLite
                        JSONObject userData = jObj.getJSONObject("userData");
                        String uid = userData.getString("id");
                        String name = userData.getString("name");
                        String email = userData.getString("email");
                        String created_at = userData.getString("created_at");

                        // Inserting row in users table
                        db.addUser(name, email, uid, created_at);

                        // Launch main activity
                        startActivity(new Intent(LoginPage.this, HomePage.class));
                        finish();
                    } else {
                        // Error in login. Get the error message
                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Login Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<String, String>();
                params.put("email", email);
                params.put("password", password);

                return params;
            }

        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

    private void showDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }



}
Spring Breaker
  • 7,846
  • 3
  • 31
  • 59
Sam
  • 49
  • 1
  • 8

1 Answers1

0

Although this is not a solution to your problem(for solution look below), refactoring the checkLogin Method will definetly help alot in finding the cause of the error. Due to the fact that the checkLogin method was way to long I've move some of the code into other methods.

Copy it, run it and let us know which line throws the error.

/**
 * function to verify login details in mysql db
 * */
private void checkLogin(final String email, final String password) {
    // Tag used to cancel the request
    String tag_string_req = "req_login";
    pDialog.setMessage("Logging in ...");
    showDialog();

    StringRequest strReq = new StringRequest(Request.Method.POST,
            AppConfig.URL_LOGIN, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(TAG, "Login Response: " + response.toString());
            hideDialog();
            checkStatus();
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "Login Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
            hideDialog();
        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            // Posting parameters to login url
            Map<String, String> params = new HashMap<String, String>();
            params.put("email", email);
            params.put("password", password);

            return params;
        }

    };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}

private void checkStatus() {
    try {
        JSONObject jObj = new JSONObject(response);
        String status = jObj.getString("status");

        // Now check status value
        if (status.equals("0")) {
            processStatusZero();
        }else if(status.equals("1")){
            processStatusOne(jObj);
        } else {
            processStatusError(jObj);
        }
    } catch (JSONException e) {
        // JSON error
        e.printStackTrace();
        Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
    }
}

private void processStatusZero() {
    Toast.makeText(getApplicationContext(), "Email or Password may be incorrect! Please try again.", Toast.LENGTH_LONG).show();
}

private void processStatusOne(JSONObject jObj) {
    // user successfully logged in
    // Create login session
    session.setLogin(true);

    // Now store the user in SQLite
    JSONObject userData = jObj.getJSONObject("userData");
    String uid = userData.getString("id");
    String name = userData.getString("name");
    String email = userData.getString("email");
    String created_at = userData.getString("created_at");

    // Inserting row in users table
    db.addUser(name, email, uid, created_at);

    // Launch main activity
    startActivity(new Intent(LoginPage.this, HomePage.class));
    finish();
}

private void processStatusError(JSONObject jObj) {
    // Error in login. Get the error message
    String errorMsg = jObj.getString("error_msg");
    Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show();
}

Now for the actual solution: you need to add AppControler to the Android Manifest. You do this by adding the following lines in your manifest file:

<application
android:name=".AppController"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">

This way AppController.getInstance() will stop returning null.

Irina Avram
  • 1,319
  • 1
  • 15
  • 30