简体   繁体   中英

android application crashing due to java.lang.NullPointerException

I am following a andorid development guide and seem to be getting a errror while trying to register an account, I am aware of the issues and the location (line 197) but I cannot seem to fix the issue please find below a copy of the logcat and my register code, If there is anymore information you need please comment and I will try and help.

04-24 21:24:32.735: E/AndroidRuntime(30368): FATAL EXCEPTION: main
04-24 21:24:32.735: E/AndroidRuntime(30368): java.lang.NullPointerException
04-24 21:24:32.735: E/AndroidRuntime(30368):    at com.loggedin.Register$ProcessRegister.onPostExecute(Register.java:197)
04-24 21:24:32.735: E/AndroidRuntime(30368):    at com.loggedin.Register$ProcessRegister.onPostExecute(Register.java:1)
04-24 21:24:32.735: E/AndroidRuntime(30368):    at android.os.AsyncTask.finish(AsyncTask.java:631)
04-24 21:24:32.735: E/AndroidRuntime(30368):    at android.os.AsyncTask.access$600(AsyncTask.java:177)
04-24 21:24:32.735: E/AndroidRuntime(30368):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
04-24 21:24:32.735: E/AndroidRuntime(30368):    at android.os.Handler.dispatchMessage(Handler.java:99)
04-24 21:24:32.735: E/AndroidRuntime(30368):    at android.os.Looper.loop(Looper.java:176)
04-24 21:24:32.735: E/AndroidRuntime(30368):    at android.app.ActivityThread.main(ActivityThread.java:5419)
04-24 21:24:32.735: E/AndroidRuntime(30368):    at java.lang.reflect.Method.invokeNative(Native Method)
04-24 21:24:32.735: E/AndroidRuntime(30368):    at java.lang.reflect.Method.invoke(Method.java:525)
04-24 21:24:32.735: E/AndroidRuntime(30368):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
04-24 21:24:32.735: E/AndroidRuntime(30368):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
04-24 21:24:32.735: E/AndroidRuntime(30368):    at dalvik.system.NativeStart.main(Native Method)
04-24 21:25:05.435: I/Process(30368): Sending signal. PID: 30368 SIG: 9

Register java

 import android.app.Activity;
 import android.app.ProgressDialog;
 import android.content.Context; 
 import android.content.Intent;
 import android.net.ConnectivityManager;
 import android.net.NetworkInfo;
 import android.os.AsyncTask;
 import android.os.Bundle;
 import android.view.View;  
 import android.widget.Button;
 import android.widget.EditText;
 import android.widget.TextView;
 import android.widget.Toast;
 import com.loggedin.internal.DatabaseHandler;
 import com.loggedin.internal.UserFunctions;
 import org.json.JSONException;
 import org.json.JSONObject;
 import java.io.IOException;
 import java.net.HttpURLConnection;
 import java.net.MalformedURLException;
 import java.net.URL;

 public class Register extends Activity {
 /**
 *  JSON Response node names.
 **/
 private static String KEY_SUCCESS = "success";
 private static String KEY_UID = "id";
 private static String KEY_FIRSTNAME = "FirstName";
 private static String KEY_LASTNAME = "LastName";
 private static String KEY_USERNAME = "Username";
 private static String KEY_EMAIL = "email";
 private static String KEY_DOB = "DOB";
 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 inputDOB;
 EditText inputPassword;
 Button registerbtn;
 TextView register_error;
 /**
 * Called when the activity is first created.
 */
 @Override
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_register);
 /**
 * Defining all layout items
 **/
    inputFirstName = (EditText) findViewById(R.id.FirstName);
    inputLastName = (EditText) findViewById(R.id.LastName);
    inputUsername = (EditText) findViewById(R.id.Username);
    inputEmail = (EditText) findViewById(R.id.email);
    inputDOB = (EditText) findViewById(R.id.DOB);
    inputPassword = (EditText) findViewById(R.id.Password);
    registerbtn = (Button) findViewById(R.id.registerbtn);
    register_error = (TextView) findViewById(R.id.register_error);
 /**
 * Button which Switches back to the login screen on clicked
 **/
    Button login = (Button) findViewById(R.id.bktologinbtn);
    login.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Intent myIntent = new Intent(view.getContext(), Login.class);
            startActivityForResult(myIntent, 0);
            finish();
        }
    });
    /**
     * 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.
     **/
    registerbtn.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(""))  && ( !inputDOB.getText().toString().equals("")) && ( !inputEmail.getText().toString().equals("")) )
            {
                if ( inputUsername.getText().toString().length() > 5 ){
                InternetAsync(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 InternetCheck extends AsyncTask<String, Boolean, 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();
            register_error.setText("Error in Network Connection");
        }
    }
   }
 private class ProcessRegister extends AsyncTask <String, String, JSONObject>{
 /**
  * Defining Process dialog
  **/
    private ProgressDialog pDialog;
    String email,Password,FirstName,LastName,DOB,Username;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        inputUsername = (EditText) findViewById(R.id.Username);
        inputPassword = (EditText) findViewById(R.id.Password);
           FirstName = inputFirstName.getText().toString();
           LastName = inputLastName.getText().toString();
            email = inputEmail.getText().toString();
            DOB = inputDOB.getText().toString();
            Username= 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(FirstName, LastName, DOB, email, Username, Password);
        return json;
    }
   @Override
    protected void onPostExecute(JSONObject json) {
   /**
    * Checks for success message.
    **/
       if (json ==null){

       }
            try {
                if (json.getString(KEY_SUCCESS) != null) {
                    register_error.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");
                        register_error.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();
                        register_error.setText("User already exists");
                    }
                    else if (Integer.parseInt(red) ==3){
                        pDialog.dismiss();
                        register_error.setText("Invalid Email id");
                    }
                }
                    else{
                    pDialog.dismiss();
                        register_error.setText("Error occured in registration");
                    }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
   }
    public void InternetAsync(View view){
        new InternetCheck().execute();
    }
    }

I can see three possibilities:

if (json ==null){

}

This is doing nothing and json could be null and

json.getString(KEY_SUCCESS)

could potentially be the culprit.

Another possibility could be the pDialog or register_error . Make sure to check for every resource before referencing, you can see everyone guessing which one it is. In fact NPE is one of the most common Exceptions, so please make sure you validate the data before using it, save yourself some headaches.

Solution:

if (json ==null){
    return; //You can potentially Log the error too, if it helps.
}

OR

if(json != null) {
    try{
        if (json.getString(KEY_SUCCESS) != null) {
        //...
}

Also, add checks for:

if(pDialog != null) {
    //Manipulate the element to do what you want.
}

and

if(register_error != null) {
    //Manipulate the element to do what you want.
}

Seems like json object is null. You should handle that in correct way. now you're just ignoring it. Here:

   /**
   * Checks for success message.
   **/
   if (json ==null){
       return; // <-- just a sample, handle null in yuor way, don't ignore it
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM