简体   繁体   中英

Null pointer exception when trying to invoke the method from another class?

Currently getting a nullpointer exception when attempting to validate a User's credentials, I believe it's being caused in the OnPostExecute method, but I cannot figure out what's causing it. Here is my BackgroundWorker class, as well as my LoginActivity. The PHP file for login return either "LoginSuccess", or "LoginFailed". The error seems to be happening when OnPostExecute is trying to invoke the methods from the Login Activity, any idea of how to fix this?

public class BackgroundWorker extends AsyncTask<String, Void, String>{
Context context;
AlertDialog alertDialog;
LoginActivity loginActivity;
BackgroundWorker (Context ctx) {
    context = ctx;
}
@Override
protected String doInBackground(String... params) {
    String type = params[0];

if(type.equals("login")) {
        //If a registered user is trying to login
        try {
            String username = params[1];
            String password = params[2];
            URL url = new URL(login_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("username", "UTF-8")+"="+URLEncoder.encode(username, "UTF-8")+"&"
                    +URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(password, "UTF-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
            String result="";
            String line="";
            while((line = bufferedReader.readLine()) != null) {
                result+=line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    } else if(type.equals("register")) {
        //If a new user to trying to register
        try {
            String str_name = params[1];
            String str_username = params[2];
            String str_password = params[3];
            String str_email = params[4];
            URL url = new URL(register_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("name", "UTF-8")+"="+URLEncoder.encode(str_name, "UTF-8")+"&"+
                    URLEncoder.encode("user_name", "UTF-8")+"="+URLEncoder.encode(str_username, "UTF-8")+"&"
                    +URLEncoder.encode("user_pass", "UTF-8")+"="+URLEncoder.encode(str_password, "UTF-8")
                    +"&"+URLEncoder.encode("user_email", "UTF-8")+"="+URLEncoder.encode(str_email, "UTF-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
            String result="";
            String line="";
            while((line = bufferedReader.readLine()) != null) {
                result+=line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    return null;
}
@Override
protected void onPreExecute() {
    alertDialog = new AlertDialog.Builder(context).create();
    alertDialog.setTitle("Login Status");
}

@Override
protected void onPostExecute(String result) {
    switch(result){
        case "LoginSuccess":
            loginActivity.OnLoginSuccess();
            break;
        case "LoginFailed":
            loginActivity.OnLoginFailed();
            break;

    }
}

@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
    }
}

LoginActivity

public class LoginActivity extends AppCompatActivity{
EditText etUsername, etPassword;
Button bLogin;
String tmpUsername;




@RequiresApi(api = Build.VERSION_CODES.M)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    etUsername = (EditText) findViewById(R.id.etUsername);
    etPassword = (EditText) findViewById(R.id.etPassword);
    bLogin = (Button) findViewById(R.id.bLogin);
    final TextView registerLink = (TextView) findViewById(R.id.tvRegisterHere);
    tmpUsername = "";

    requestPermissions();

}

@RequiresApi(api = Build.VERSION_CODES.M)
private boolean requestPermissions() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[]{
                Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.INTERNET
        }, 1 );
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return true;
    } else {
        return false;
    }

}


public void OnLogin(View view){
    String username = etUsername.getText().toString();
    String password = etPassword.getText().toString();
    String type = "login";
    tmpUsername = username;
    BackgroundWorker loginRequest = new BackgroundWorker(this);
    loginRequest.execute(type, username, password);

}
public void OpenReg(View view) {
    startActivity(new Intent(this, RegisterActivity.class));
}


public void OnLoginSuccess(){
    Intent intent = new Intent(LoginActivity.this, ViewGroupActivity.class);
    intent.putExtra("username", tmpUsername);
    startActivity(intent);

}

public void OnLoginFailed(){
    Toast.makeText(this, "Username or password doesn't match.  Please try again",Toast.LENGTH_SHORT).show();
}

Here is my logcat

04-04 15:02:11.180 6775-6775/com.example.myproject.findme E/AndroidRuntime: 
FATAL EXCEPTION: main
Process: com.example.myproject.findme, PID: 6775
java.lang.NullPointerException: Attempt to invoke virtual method 
'java.lang.String android.content.Context.getPackageName()' on a null object 
reference
    at android.content.ContextWrapper.getPackageName(ContextWrapper.java:135)
    at android.widget.Toast.<init>(Toast.java:114)
    at android.widget.Toast.makeText(Toast.java:277)
    at android.widget.Toast.makeText(Toast.java:267)
    at com.example.myproject.findme.LoginActivity.OnLoginFailed(LoginActivity.java:97)
    at com.example.myproject.findme.BackgroundWorker.onPostExecute(BackgroundWorker.java:288)
    at com.example.myproject.findme.BackgroundWorker.onPostExecute(BackgroundWorker.java:25)
    at android.os.AsyncTask.finish(AsyncTask.java:695)
    at android.os.AsyncTask.-wrap1(Unknown Source:0)
    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6494)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

As I noticed you did not initialize your loginActivity instance variable. You can do that witb setter method or in constructor of your BackgroundWorker class. Currently you are passing only the reference of Context object. You should write you BackgroundWorker constructor like this

BackgroundWorker(LoginActivity  loginActivity){
     this.loginActivity = loginActivity;
}  

and in login activity pass param - this - like that

new BackgroundWorker(this)

and you also can use the loginActivity reference as a context in your BackgroundWorker.

it will work 100%.

but it will be better if you will use interface methods as callback.

for example:

interface BackgroundWorkerCallback{
      Contrxt getContext();
      void success();
      void failed();
}  

implement this interface in your LoginActivity override last two methods as you would like and the first one should return context reference.

in you BackgroundWorker class

change the constructor like this:

 private BackgroundWorkerCallback    callback;
 public  BackgroundWorker(BackgroundWorkerCallback callback){
         this.callback = callback;
 }

and in your post execute method call methods like this

if success callback.success();
else if failed callback.failed();

and for context use

callback.getContext();

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