arinze
arinze

Reputation: 449

Android Okhttp asynctask post excute error?

I am trying to get login details using asyntask in android but it is giving me errors occasionally. Sometimes it goes through sometimes it does not. It keeps directing me to my Jsonobject in my post execute. and i don know why.

This is my java class.

  AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() {
                protected void onPreExecute() {
                    super.onPreExecute();
                    pDialog = new ProgressDialog(Maint.this);
                    pDialog.setMessage("getting detail...");
                    pDialog.setIndeterminate(false);
                    pDialog.setCancelable(true);
                    pDialog.show();
                }

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


                    try {
                        RequestBody formBody = new FormBody.Builder()
                                .add("email", acct.getEmail())
                                .add("google_id", regId)
                                .build();
                        final Request request = new Request.Builder()
                                .url(log)
                                .post(formBody)
                                .build();
                        Response response;
                        response = client.newCall(request).execute();
                        return   response.body().string();
                    } catch (Exception e) {
                        e.printStackTrace();
                        return null;
                    }

                }

                @Override
                protected void onPostExecute(String s) {
                    super.onPostExecute(s);
                    if (pDialog != null) {
                        pDialog.dismiss();
                    }
                    String jsonData = s;
                    try {
                        JSONObject Jobject = new JSONObject(jsonData);
                        String pic = "";
                        if (acct.getPhotoUrl() == null || acct.getPhotoUrl().toString().isEmpty() || acct.getPhotoUrl().toString().contentEquals("")) {
                            pic = "https://lh3.googleusercontent.com/-5O1D0RBwhGE/AAAAAAAAAAI/AAAAAAAAAUg/Lm43fa7Sbgg/s36-p-k-rw-no/photo.jpg";
                        } else {
                            pic = acct.getPhotoUrl().toString();
                        }

                        SharedPreferences sp = PreferenceManager
                                .getDefaultSharedPreferences(Maint.this);
                        SharedPreferences.Editor edit = sp.edit();
                        edit.putString("firstname", acct.getGivenName());
                        edit.putString("lastname", acct.getFamilyName());
                        edit.putString("email", acct.getEmail());
                        edit.putString("url", pic);
                        edit.putString("google_id",regId);
                        edit.putString("check",Jobject.getString("success"));
                        edit.commit();
                        Intent uo = new Intent(getApplicationContext(), LoginActivity.class);
                        finish();
                        startActivity(uo);


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

This is my error

java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
                                                                                   at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
                                                                                   at org.json.JSONTokener.nextValue(JSONTokener.java:94)
                                                                                   at org.json.JSONObject.<init>(JSONObject.java:156)
                                                                                   at org.json.JSONObject.<init>(JSONObject.java:173)
                                                                                   at com.obi.thinker.fringes.Maint$2.onPostExecute(Maint.java:223)
                                                                                   at com.obi.thinker.fringes.Maint$2.onPostExecute(Maint.java:182)
                                                                                   at android.os.AsyncTask.finish(AsyncTask.java:651)
                                                                                   at android.os.AsyncTask.-wrap1(AsyncTask.java)
                                                                                   at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:111)
                                                                                   at android.os.Looper.loop(Looper.java:207)
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:5683)
                                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)

Upvotes: 0

Views: 646

Answers (1)

teck wei
teck wei

Reputation: 1385

Actually if you want to do a asynchronous with OKHTTP you should use it own asynchronous method

client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {

                }
            });

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            final String res = response.body().string().trim();
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {

                }

            });
        }
    });

NOTE:If you wan to update your UI you need to use runOnUIThread else it will crash your app. If you want to do a synchronous with OKHTTP there is no point to use asynctask. If you want to learn more about the difference check this difference between async and sync.

Based on your logcat your crash it happen in the line 116 or 94. The problem is not happening on OKHTTP it happen you try to access a null object with the method length(). For example

String text = null;
if(text.length > 0){ //the app will throw a NPE(Null Pointer Exception) error.
    Log.d("TAG","ok");
}

For best pratice you can do a check

if(text != null){
    if(text.length > 0){
    }
}

For your case on the onPostExecute() method

@Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                if (pDialog != null) {
                    pDialog.dismiss();
                }

                if(s == null){
                     Log.d("TAG","reponse return null");                      
                     return;
                }

                String jsonData = s;
                try {
                    JSONObject Jobject = new JSONObject(jsonData);
                    String pic = "";
                    if (acct.getPhotoUrl() == null || acct.getPhotoUrl().toString().isEmpty() || acct.getPhotoUrl().toString().contentEquals("")) {
                        pic = "https://lh3.googleusercontent.com/-5O1D0RBwhGE/AAAAAAAAAAI/AAAAAAAAAUg/Lm43fa7Sbgg/s36-p-k-rw-no/photo.jpg";
                    } else {
                        pic = acct.getPhotoUrl().toString();
                    }

                    SharedPreferences sp = PreferenceManager
                            .getDefaultSharedPreferences(Maint.this);
                    SharedPreferences.Editor edit = sp.edit();
                    edit.putString("firstname", acct.getGivenName());
                    edit.putString("lastname", acct.getFamilyName());
                    edit.putString("email", acct.getEmail());
                    edit.putString("url", pic);
                    edit.putString("google_id",regId);
                    edit.putString("check",Jobject.getString("success"));
                    edit.commit();
                    Intent uo = new Intent(getApplicationContext(), LoginActivity.class);
                    finish();
                    startActivity(uo);


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

The crash will not happen.

Upvotes: 1

Related Questions