0

I was following this tutorial (http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/) to create a user login and registration for an application using volly. Everything works fine when I make it a stand alone app with no other features. The issue starts when I try integrate it with another application.

I am copying the classes produced from the tutorial straight into an existing project but I am getting a null pointer. Now before I go any further, I know what a null pointer is and I know how to solve them.

I am new-ish to Android and I am having trouble finding this one and would greatly appreciate some help with it rather then people just directing me to here -What is a NullPointerException, and how do I fix it? - as I have already looked at this but it still doesnt help me locate this error.

Login Activity

    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;

    import com.android.volley.Request.Method;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.toolbox.StringRequest;

    import org.json.JSONException;
    import org.json.JSONObject;

    import java.util.HashMap;
    import java.util.Map;

    import com.example.rory.pocketchef.R;
    import com.example.rory.pocketchef.app.AppConfig;
    import com.example.rory.pocketchef.app.AppController;
    import com.example.rory.pocketchef.helper.SQLiteHandler;
    import com.example.rory.pocketchef.helper.SessionManager;

    public class LoginActivity extends Activity {
        private static final String TAG = RegisterActivity.class.getSimpleName();
        private Button btnLogin;
        private Button btnLinkToRegister;
        private EditText inputEmail;
        private EditText inputPassword;
        private ProgressDialog pDialog;
        private SessionManager session;
        private SQLiteHandler db;

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

            inputEmail = (EditText) findViewById(R.id.email);
            inputPassword = (EditText) findViewById(R.id.password);
            btnLogin = (Button) findViewById(R.id.btnLogin);
            btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);

            // 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(LoginActivity.this, FirstActivity.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);
                    } 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) {
                    Intent i = new Intent(getApplicationContext(),
                            RegisterActivity.class);
                    startActivity(i);
                    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(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);
                        boolean error = jObj.getBoolean("error");

                        // Check for error node in json
                        if (!error) {
                            // user successfully logged in
                            // Create login session
                            session.setLogin(true);

                            // Now store the user in SQLite
                            String uid = jObj.getString("uid");

                            JSONObject user = jObj.getJSONObject("user");
                            String name = user.getString("name");
                            String email = user.getString("email");
                            String created_at = user
                                    .getString("created_at");

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

                            // Launch main activity
                            Intent intent = new Intent(LoginActivity.this, FirstActivity.class);
                            startActivity(intent);
                            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();
        }
    }

AppController

import android.app.Application;
    import android.text.TextUtils;

    import com.android.volley.Request;
    import com.android.volley.RequestQueue;
    import com.android.volley.toolbox.Volley;

    public class AppController extends Application {

        public static final String TAG = AppController.class.getSimpleName();

        private RequestQueue mRequestQueue;

        private static AppController mInstance;

        @Override
        public void onCreate() {
            super.onCreate();
            mInstance = this;
        }

        public static synchronized AppController getInstance() {
            return mInstance;
        }

        public RequestQueue getRequestQueue() {
            if (mRequestQueue == null) {
                mRequestQueue = Volley.newRequestQueue(getApplicationContext());
            }

            return mRequestQueue;
        }

        public <T> void addToRequestQueue(Request<T> req, String tag) {
            req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
            getRequestQueue().add(req);
        }

        public <T> void addToRequestQueue(Request<T> req) {
            req.setTag(TAG);
            getRequestQueue().add(req);
        }

        public void cancelPendingRequests(Object tag) {
            if (mRequestQueue != null) {
                mRequestQueue.cancelAll(tag);
            }
        }
    }

Android Manifest

<uses-permission android:name="android.permission.INTERNET" />

<android:uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<android:uses-permission android:name="android.permission.READ_PHONE_STATE" />
<android:uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_logo"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/MyMaterialTheme" >
    <activity
        android:name=".activity.LoginActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".SingleRecipeDisplay"
        android:label="@string/title_activity_single_recipe_display"
        android:theme="@style/MyMaterialTheme" >
    </activity>
    <activity android:name=".Favourites" >
    </activity>
    <activity android:name=".Help" >
    </activity>
    <activity android:name=".activity.RegisterActivity">
    </activity>
</application>

Error

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.rory.pocketchef.app.AppController.addToRequestQueue(com.android.volley.Request, java.lang.String)' on a null object reference 02-22 15:03:54.296 13823-13823/com.example.rory.pocketchef E/AndroidRuntime: at com.example.rory.pocketchef.activity.LoginActivity.checkLogin(LoginActivity.java:183) 02-22 15:03:54.296 13823-13823/com.example.rory.pocketchef E/AndroidRuntime: at
com.example.rory.pocketchef.activity.LoginActivity.access$200(LoginActivity.java:30) 02-22 15:03:54.296 13823-13823/com.example.rory.pocketchef E/AndroidRuntime: at com.example.rory.pocketchef.activity.LoginActivity$1.onClick(LoginActivity.java:78)

Community
  • 1
  • 1
JJSmith
  • 1,833
  • 4
  • 17
  • 26

1 Answers1

1

Your application instance is null. It's Singleton class but instance is never created.

Problem is that you missed to add name in <application> tag. Name should be AppController or even better full package path of AppController.

[EDIT]

And use this instead getApplicationContext() in AppController.

Boban S.
  • 1,662
  • 13
  • 16
  • I have the android manifest file in the question, is there another one you need to see? – JJSmith Feb 22 '16 at 15:17
  • You added the right file, but you forgot the attribute he mentioned. – stefana Feb 22 '16 at 15:27
  • thanks for the suggestion I really do appreciate the help, when I made the change i got another null error on `mRequestQueue = Volley.newRequestQueue(getApplicationContext());` in the AppController class? – JJSmith Feb 22 '16 at 16:14
  • Sorry, I first started writing question then I saw the manifest and forgot to delete the sentence. – Boban S. Feb 22 '16 at 16:52
  • Thanks for all the help guys I got it sorted, +1 – JJSmith Feb 22 '16 at 17:51