-3

I am trying to make a Register system for android. It registers users into the database and they receive an email confirmation, however the application crashes and closes.

I have checked the forum of how to correct NullPointer errors, however I am struggling, therefore could someone please offer me a helping hand. I have checked the post .What is a Null Pointer Exception, and how do I fix it?. Still cannot find my solution please advise and help.

CatLog - Error Messages

E/JSON Parser﹕ Error parsing data org.json.JSONException: Value 2015-12-09 of type java.lang.String cannot be converted to JSONObject

E/AndroidRuntime﹕ FATAL EXCEPTION: mainPID: 2386 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference

at com.app.tourist.Register$ProcessRegister.onPostExecute(Register.java:214

at com.app.tourist.Register$ProcessRegister.onPostExecute(Register.java:171)

   private class ProcessRegister extends AsyncTask<String, String, JSONObject> { - Line 171: Gving Error Here.

   if (json.getString(KEY_SUCCESS) != null) { - Line 214: Giving Error.

Register.Java File

public class Register extends Activity {


    /**
     *  JSON Response node names.
     **/


    private static String KEY_SUCCESS = "success";
    private static String KEY_UID = "uid";
    private static String KEY_FIRSTNAME = "fname";
    private static String KEY_LASTNAME = "lname";
    private static String KEY_USERNAME = "uname";
    private static String KEY_EMAIL = "email";
    private static String KEY_CREATED_AT = "created_at";
    private static String KEY_ERROR = "error";

    /**
     * Defining layout items.
     **/

    EditText inputFirstName;
    EditText inputLastName;
    EditText inputUsername;
    EditText inputEmail;
    EditText inputPassword;
    ImageButton btnRegister;
    TextView registerErrorMsg;


    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);

        /**
         * Defining all layout items
         **/
        inputFirstName = (EditText) findViewById(R.id.fname);
        inputLastName = (EditText) findViewById(R.id.lname);
        inputUsername = (EditText) findViewById(R.id.uname);
        inputEmail = (EditText) findViewById(R.id.email);
        inputPassword = (EditText) findViewById(R.id.pword);
        btnRegister = (ImageButton) findViewById(R.id.Registerbtn);
        registerErrorMsg = (TextView) findViewById(R.id.register_error);

        /**
         * Register Button click event.
         * A Toast is set to alert when the fields are empty.
         * Another toast is set to alert Username must be 5 characters.
         **/



        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (  ( !inputUsername.getText().toString().equals("")) && ( !inputPassword.getText().toString().equals("")) && ( !inputFirstName.getText().toString().equals("")) && ( !inputLastName.getText().toString().equals("")) && ( !inputEmail.getText().toString().equals("")) )
                {
                    if ( inputUsername.getText().toString().length() > 4 ){
                        NetAsync(view);

                    }
                    else
                    {
                        Toast.makeText(getApplicationContext(),
                                "Username should be minimum 5 characters", Toast.LENGTH_SHORT).show();
                    }
                }
                else
                {
                    Toast.makeText(getApplicationContext(),
                            "One or more fields are empty", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    /**
     * Async Task to check whether internet connection is working
     **/

    private class NetCheck extends AsyncTask<String,String,Boolean>
    {
        private ProgressDialog nDialog;

        @Override
        protected void onPreExecute(){
            super.onPreExecute();
            nDialog = new ProgressDialog(Register.this);
            nDialog.setMessage("Loading..");
            nDialog.setTitle("Checking Network");
            nDialog.setIndeterminate(false);
            nDialog.setCancelable(true);
            nDialog.show();
        }

        @Override
        protected Boolean doInBackground(String... args){


/**
 * Gets current device state and checks for working internet connection by trying Google.
 **/
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            if (netInfo != null && netInfo.isConnected()) {
                try {
                    URL url = new URL("http://www.google.com");
                    HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
                    urlc.setConnectTimeout(3000);
                    urlc.connect();
                    if (urlc.getResponseCode() == 200) {
                        return true;
                    }
                } catch (MalformedURLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            return false;

        }
        @Override
        protected void onPostExecute(Boolean th){

            if(th == true){
                nDialog.dismiss();
                new ProcessRegister().execute();
            }
            else{
                nDialog.dismiss();
                registerErrorMsg.setText("Error in Network Connection");
            }
        }
    }


    private class ProcessRegister extends AsyncTask<String, String, JSONObject> {

        /**
         * Defining Process dialog
         **/
        private ProgressDialog pDialog;

        String email,password,fname,lname,uname;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            inputUsername = (EditText) findViewById(R.id.uname);
            inputPassword = (EditText) findViewById(R.id.pword);
            fname = inputFirstName.getText().toString();
            lname = inputLastName.getText().toString();
            email = inputEmail.getText().toString();
            uname= inputUsername.getText().toString();
            password = inputPassword.getText().toString();
            pDialog = new ProgressDialog(Register.this);
            pDialog.setTitle("Contacting Servers");
            pDialog.setMessage("Registering ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected JSONObject doInBackground(String... args) {


            UserFunctions userFunction = new UserFunctions();
            JSONObject json = userFunction.registerUser(fname, lname, email, uname, password);

            return json;


        }
        @Override
        protected void onPostExecute(JSONObject json) {
            /**
             * Checks for success message.
             **/
            try {
                if (json.getString(KEY_SUCCESS) != null) {
                    registerErrorMsg.setText("");
                    String res = json.getString(KEY_SUCCESS);

                    String red = json.getString(KEY_ERROR);

                    if(Integer.parseInt(res) == 1){
                        pDialog.setTitle("Getting Data");
                        pDialog.setMessage("Loading Info");

                        registerErrorMsg.setText("Successfully Registered");


                        DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                        JSONObject json_user = json.getJSONObject("user");

                        /**
                         * Removes all the previous data in the SQlite database
                         **/

                        UserFunctions logout = new UserFunctions();
                        logout.logoutUser(getApplicationContext());
                        db.addUser(json_user.getString(KEY_FIRSTNAME),json_user.getString(KEY_LASTNAME),json_user.getString(KEY_EMAIL),json_user.getString(KEY_USERNAME),json_user.getString(KEY_UID),json_user.getString(KEY_CREATED_AT));
                        /**
                         * Stores registered data in SQlite Database
                         * Launch Registered screen
                         **/

                        Intent registered = new Intent(getApplicationContext(), Registered.class);

                        /**
                         * Close all views before launching Registered screen
                         **/
                        registered.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        pDialog.dismiss();
                        startActivity(registered);


                        finish();
                    }

                    else if (Integer.parseInt(red) ==2){
                        pDialog.dismiss();
                        registerErrorMsg.setText("User already exists");
                    }
                    else if (Integer.parseInt(red) ==3){
                        pDialog.dismiss();
                        registerErrorMsg.setText("Invalid Email id");
                    }

                }


                else{
                    pDialog.dismiss();

                    registerErrorMsg.setText("Error occured in registration");
                }

            } catch (JSONException e) {
                e.printStackTrace();


            }
        }}
    public void NetAsync(View view){
        new NetCheck().execute();
    }}

UserFuction.java File

/**
     * Function to  Register
     **/
    public JSONObject registerUser(String fname, String lname, String email, String uname, String password){
        // Building Parameters
        List params = new ArrayList();
        params.add(new BasicNameValuePair("tag", register_tag));
        params.add(new BasicNameValuePair("fname", fname));
        params.add(new BasicNameValuePair("lname", lname));
        params.add(new BasicNameValuePair("email", email));
        params.add(new BasicNameValuePair("uname", uname));
        params.add(new BasicNameValuePair("password", password));
        JSONObject json = jsonParser.getJSONFromUrl(registerURL,params);
        return json;
    }
J.Doe
  • 59
  • 6

1 Answers1

0

Apperantly following line retuns null. Please check it.

JSONObject json = userFunction.registerUser(fname, lname, email, uname, password);
  • It enters user information into the database once they register and it send them an email confirmation, however I do not understand why the application crashes could you please advise?. – J.Doe Dec 15 '15 at 12:12
  • As I don't have src for registerUser(), I can only suggest you to debug and check what happens in that method. – Swapnil Chaudhari Dec 15 '15 at 12:15
  • I have added the userfuction.registeruser file. – J.Doe Dec 15 '15 at 12:22
  • {"tag":"register","success":1,"error":0,"user":{"fname":"Katherine","lname":"Johnson","email":"Katherine-johnson@gmail.com","uname":"Kathy","uid":"5670166f83c2b1.35739889","created_at":"2015-12-15 13:32:31"}} 12-15 13:31:46.110 2346-2390/com.app.tourist E/JSON Parser﹕ Error parsing data org.json.JSONException: Value 2015-12-15 of type java.lang.String cannot be converted to JSONObject 1 – J.Doe Dec 15 '15 at 13:36
  • JSONObject json = jsonParser.getJSONFromUrl(registerURL,params); Does this line returns response you mentioned earlier? I belive I will return null. – Swapnil Chaudhari Dec 16 '15 at 13:53
  • Could you please assist in how I am able to rectify this problem, – J.Doe Dec 17 '15 at 10:30
  • Can you debug starting from userFunction.registerUser(). Try to see all values of all the variables. Check for "", null. – Swapnil Chaudhari Dec 17 '15 at 11:48
  • I have started dubugging from here and below is the message. Exception = {GaiException@3659} error = 8 functionName = {String@3673} "android_getaddrinfo" cause = {GaiException@3659} "android.system.GaiException: android_getaddrinfo failed: EAI_NONAME (hostname nor servname provided, or not known)" detailMessage = null stackState = {Object[21]@3674} stackTrace = {StackTraceElement[0]@3675} suppressedExceptions = {Collections$EmptyList@3676} size = 0 shadow$_klass_ = {Class@1984} "class android.system.GaiException" shadow$_monitor_ = -2106033225 – J.Doe Dec 18 '15 at 13:21
  • JSONObject json = jsonParser.getJSONFromUrl(registerURL,params); that is making the null value. could you please advise or help please?. – J.Doe Dec 18 '15 at 18:16
  • After looking at your previous logs it appear thet you might not have mentioned server's address correctly. You should also consider adding check for null.It may happen that due to bad network your app may not communicate with server and it should not crash. – Swapnil Chaudhari Dec 19 '15 at 15:29
  • I have as it works for login and change password, however not for register. could you please help and find the issue of why the application just crashes. – J.Doe Dec 19 '15 at 19:46
  • Debug and check how the url is formed? Check if the url is correct. For clarification you can compare it with login url by debugging. – Swapnil Chaudhari Dec 21 '15 at 06:30
  • when debugging both it looks like both of the URL are same and not different. When I log in and then click on register and register with new details the app does not crash as it shows the orignial person logged in details and therefore does not crash. Could you atleast downloald the application on your system and try to resolve it for me. This website got similar tutorial like the one I followed. http://www.learn2crack.com/2013/08/develop-android-login-registration-with-php-mysql.html – J.Doe Dec 21 '15 at 08:39