-1

I am trying to login the user through networking by using OkHttp library to send request and getting response. After running these when I open app and enter email and password as input and press the login button, my app crashes.

LoginFragment:

 public void onClick(View view) {
            String a=ed1.getText().toString();
            String b=ed2.getText().toString();
            Log.e("sas", "onClick: "+a );
                NetworkRequestAndResponse asyncTask = new NetworkRequestAndResponse(getActivity());
                asyncTask.execute(a,b);
        }
    });
    return view;

AsyncTask:

    public class NetworkRequestAndResponse extends AsyncTask<String,String,String> {
    Context context;

    public NetworkRequestAndResponse(Context context){
        this.context = context.getApplicationContext();
    }

    @Override
    protected String doInBackground(String... params) {
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody= new FormBody.Builder().add("email",params[0])
                        .add("password",params[1]).build();
        Request request = new Request.Builder().url("http://192.168.1.8:8011/api/check")
                        .post(requestBody).build();
        Log.e("asd", "doInBackground: "+request );
        Response response=null;
        try {
            response = okHttpClient.newCall(request).execute();
          return response.body().string();
        } catch (RuntimeException|IOException e){
            Log.e("455", "doInBackground: ",e );
        }
        finally {
            response.close();
        }
        return null;

    }

    @Override
    protected void onPostExecute(String obj){

        if (obj.equals("true")){
            Intent intent = new Intent(context, WelcomeActivity.class);
            context.startActivity(intent);
        }else{
            Toast.makeText(context,"Invalid Email or Password",Toast.LENGTH_SHORT).show();
        }
    }
}

MainActivity:

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
    LoginFragment obj = new LoginFragment();
    fragmentManager.beginTransaction().add(R.id.content,obj).commit();
    MessagesFragment messagesFragment = new MessagesFragment();
}
}

Error: enter image description here

Chirag Jain
  • 628
  • 11
  • 24
Haider
  • 99
  • 1
  • 13

3 Answers3

1

As the exception says ..Attempt to invoke virtual method on null object reference. It may be caused by the exception, if occurred in try block .. if exception occurs in a try block than it will go straight into finally block after catch block .. And in that case when it tried to close the response (which will be null), the above exception occurs.

Hobbit
  • 601
  • 1
  • 9
  • 22
0

Understandably, you want to ensure the connection is closed if there is an error. However the problem is that when any part of response = okHttpClient.newCall(request).execute(); throws an exception, the assignment will not occur. In such a situation, response will be null when you attempt to close it in the finally block.

The biggest part of the problem is that you are doing to much in a single line of code. Break this line up so that there are better chances of initializing response successfully before an exception is thrown.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
0

I strongly recommend Retrofit library for network calls. It does all asynchronous stuff for you (you don't need to use AsyncTask), it is super easy to use, has a great API and it is widely used in Android community.

As well it works very well with OkHttp.

Going back to your code problem occurs in try catch block - response.close() is called on null object. Can't say why, but it is possible that line okHttpClient.newCall(request).execute(); throws exception.

chris
  • 53
  • 1
  • 5