Null Pointer exception

时间:2017-08-05 11:56:06

标签: android android-asynctask nullpointerexception

I am trying do HTTP POST using AsyncTask. I have to create Response class, because we cannot extend more than one class. In Response class, I take response of HTTP request, then start new activities according to response. Line: responseClass.responseFunction(response); is throwing NullPointer Exception. How can I take response from login method?

public class Login extends AsyncTask <String, Void, Void>  {

    Response responseClass = new Response ();

    @Override
    protected Void doInBackground(String... strings) {
        String email = strings[0];
        String password = strings[1];

        login(email, password);

        return null;
    }

    public void login(String email, String password) {
        HttpURLConnection connection;
        OutputStreamWriter request = null;

        URL url = null;
        String response = null;
        String parameters = "email=" + email + "&password=" + password;

        try {
            url = new URL("url");
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestMethod("POST");

            request = new OutputStreamWriter(connection.getOutputStream());
            request.write(parameters);
            request.flush();
            request.close();
            String line = "";
            InputStreamReader isr = new InputStreamReader(connection.getInputStream());
            BufferedReader reader = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            System.out.println("parameter: " + parameters);
            // Response from server after login process will be stored in response variable.
            response = sb.toString();
            isr.close();
            reader.close();
        } catch (IOException e) {
            // Error

        }
        System.out.print("response" +response);
        responseClass.responseFunction(response);

    }

    class Response extends AppCompatActivity{

        public void responseFunction(String response){

           if(response.charAt(0) == '1'){

            Toast.makeText(getApplicationContext(), "e-mail veya şifre hatalı!", Toast.LENGTH_LONG).show();

        }
        else if(response.charAt(0) == '0'){
            System.out.print("Sonucc1");
            Toast.makeText(getApplicationContext(), "Başarıyla giriş yapıldı!", Toast.LENGTH_LONG).show();

            //session.createLoginSession(email,password);
            Intent intent = new Intent(this, Amount.class);
            startActivity(intent);
        }
        else if(response.charAt(0)== '2'){
           Toast.makeText(getApplicationContext(), "Geçerli bir e-mail adresi giriniz!", Toast.LENGTH_LONG).show();
        }
        else if(response.charAt(0)=='3'){
            Toast.makeText(getApplicationContext(), "Şifre 6 karakterden kısa olamaz!", Toast.LENGTH_LONG).show();


            }
        }

    }
}

Here is LogCat:

 E/AndroidRuntime: FATAL EXCEPTION: main
                                                       Process: com.example.merve.tev, PID: 20768
                                                       java.lang.NullPointerException
                                                           at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:109)
                                                           at com.example.merve.tev.Login$Response.responseFunction(Login.java:97)
                                                           at com.example.merve.tev.Login.login(Login.java:82)
                                                           at com.example.merve.tev.Login.doInBackground(Login.java:31)
                                                           at com.example.merve.tev.LoginActivity$1.onClick(LoginActivity.java:54)
                                                           at android.view.View.performClick(View.java:4438)
                                                           at android.view.View$PerformClick.run(View.java:18422)
                                                           at android.os.Handler.handleCallback(Handler.java:733)
                                                           at android.os.Handler.dispatchMessage(Handler.java:95)
                                                           at android.os.Looper.loop(Looper.java:136)
                                                           at android.app.ActivityThread.main(ActivityThread.java:5017)
                                                           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:779)
                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
                                                           at dalvik.system.NativeStart.main(Native Method)

Line 97: Toast.makeText(getApplicationContext(), "Başarıyla giriş yapıldı!", Toast.LENGTH_LONG).show();

2 个答案:

答案 0 :(得分:0)

As pointed out by @Tim in the comments, you just need to initialise your responseClass variable. Maybe you would like to do this as follows :

public class Login extends AsyncTask <String, Void, Void>  {

    Response responseClass = new Response(); // initialisation

    @Override
    protected Void doInBackground(String... strings) {
       ...
       ...

答案 1 :(得分:0)

发生错误是因为您始终在String response = null;处为响应字符串设置null。您没有为异常提供任何字符串。因此,每次代码面临异常时,responseClass.responseFunction(response);都会收到null字符串。然后它将抛出Null Pointer Exception。

public void login(String email, String password) {
   ...
   // You always set response as null
   String response = null;
   try {
      ...
      StringBuilder sb = new StringBuilder();
      while ((line = reader.readLine()) != null) {
         sb.append(line + "\n");
      }
      ...
      response = sb.toString();
          ...
   } catch (IOException e) {
      // Error
      // But here you don't set any string for response
   }

   // Hence the response will be null an throw an exception.
   System.out.print("response" +response);
   responseClass.responseFunction(response);
}