Android Okhttp asynctask发布执行错误?

时间:2017-05-21 12:58:11

标签: android android-asynctask okhttp3

我试图在android中使用asyntask获取登录详细信息,但它偶尔会给我错误。有时它经历有时它没有。它一直在我的帖子执行中指导我的Jsonobject。而且我不知道为什么。

这是我的java课程。

  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();

这是我的错误

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)

1 个答案:

答案 0 :(得分:0)

实际上,如果你想与OKHTTP进行异步,你应该使用它自己的异步方法

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() {

                }

            });
        }
    });

注意:如果您要更新UI,则需要使用runOnUIThread否则会导致应用崩溃。如果要与OKHTTP进行同步,则无需使用asynctask。如果您想了解有关差异的更多信息,请查看此difference between async and sync

基于您的logcat,您的崩溃发生在第116或94行。问题是在OKHTTP上没有发生,您尝试使用方法length()访问空对象。例如

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

为了获得最佳实践,您可以进行检查

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

适用于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();
                }
            }

崩溃不会发生。