操作onPostExecute()的结果/ Logcat不显示任何内容

时间:2019-07-29 12:29:55

标签: android android-fragments android-asynctask

我在一个Fragment中执行一个AsyncTask,我想操纵onPostExecute()的结果。为了做到这一点,我遵循了How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

我现在需要通过新的Request.Builder()对其进行操作。这就是我崩溃的地方。我无法执行以下代码行:

mResponseBody = Objects.requireNonNull(mClient.newCall(mRequest).execute().body().string();

当我无法通过时有人可以向我解释吗?知道我需要它才能继续。

AsyncTask

  private class IOAsyncTask extends AsyncTask<String, Void, String> {

            private AsyncResponse mDelegate;

            public IOAsyncTask(AsyncResponse delegate) {
                this.mDelegate = delegate;
            }

            @Override
            protected String doInBackground(String... index) {
                try {
                    int mMaxSize = 50;

                    for (int i = 20; i < mMaxSize; i += 20) {

                        RequestBody mFormBody = new MultipartBody.Builder()
                                .setType(MultipartBody.FORM)
                                .addFormDataPart(ConstantsClass.TRI, "DESC")
                                .addFormDataPart(ConstantsClass.TRI_COLONNE, "0")
                                .addFormDataPart(ConstantsClass.STATUT, "2")
                                .addFormDataPart(ConstantsClass.REPONSE, "0")
                                .build();

                        Request mRequest = new Request.Builder()
                                .url(ConstantsClass.URL_LISTE)
                                .post(mFormBody)
                                .build();

                        Response mResponse = mClient.newCall(mRequest).execute();

                        if (mResponse.code() != 200) {
                            this.cancel(true);

                            ArrayList<Application> mApplicationArray = new ArrayList<>();
                            mDataCurrentApplication.put(index[0], mApplicationArray);
                            break;
                        } else {
                            mResponseBody = mResponse.body().string();
                        }

                    }
                } catch (IOException e) {
                    e.getMessage();
                }

                return mResponseBody;
            }

            @Override
            protected void onPostExecute(String response) {

                try {
                    JSONArray mJSONArray = new JSONArray(response);

                    if (mJSONArray.length() != 0) {

                        for (int i = 0; i < mJSONArray.length(); i++) {
                            JSONObject mApplicationJSON = mJSONArray.getJSONObject(i);

                            Application mApplication = new Application(
                                    mApplicationJSON.getInt("ID"),
                                    mApplicationJSON.getString("Reference"),
                                    new Delay(mApplicationJSON.getString("Delai"), mApplicationJSON.getInt("Credits_Utilises"), mApplicationJSON.getString("Date_Reponse_Estime")),
                                    mApplicationJSON.getString("Date_Demande"),
                                    mApplicationJSON.getString("Statut"),
                                    null,
                                    Arrays.asList(mApplicationJSON.getString("Photo")),
                                    new Article(
                                            new Brand(mApplicationJSON.getInt("ID_Marque"), mApplicationJSON.getString("Marque")),
                                            mApplicationJSON.getString("Marque"),
                                            mApplicationJSON.getString("Categorie"),
                                            mApplicationJSON.getString("No_Marquage"),
                                            mApplicationJSON.getString("Attestation")
                                    )
                            );
                            mListOfApplications.add(mApplication);
                        }
                    } else {
                        mNoDataTV = (TextView) mView.findViewById(R.id.fragmentAnsweredApplicationNoDataTV);
                        mNoDataTV.setText(R.string.noData);
                    }
                } catch (JSONException e) {
                    e.getMessage();
                }

                try {
                    mDelegate.processFinish(mListOfApplications);
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }
        }

在onPostExecute()之后立即调用其结果的方法

     @Override
        public void processFinish(ArrayList output) throws IOException, JSONException {
            // Scan the whole tab
            for (int i = 0; i < output.size(); i++) {

                Application mApplication = (Application) output.get(i);

                Request mRequest = new Request.Builder()
                        .url(ConstantsClass.URL_EXPERTISE + mApplication.getmReference())
                        .get()
                        .build();

    // CAN'T EXECUTE NEXT LINE

                mResponseBody = Objects.requireNonNull(mClient.newCall(mRequest).execute().body()).string();

                JSONArray mJSONArray = new JSONArray(mResponseBody);

                if (mJSONArray.length() != 0) {
                    for (int j = 0; j < mJSONArray.length(); j++) {
                        JSONObject mObject = mJSONArray.getJSONObject(j);

                        ArrayList<String> mListOfPhotos = new ArrayList<>();
                        mListOfPhotos.add(mObject.getString("Photo"));

                        mListOfApplications.get(j).setmListOfViews(mListOfPhotos);
                    }

                }
            }

            mAdapter.setmListOfApplications(mListOfApplications);
            mRecyclerView.setAdapter(mAdapter);

Logcat显示以下内容:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.applicationpro, PID: 28440
    android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1318)
        at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:111)
        at java.net.SocketOutputStream.write(SocketOutputStream.java:157)
        at okio.Okio$1.write(Okio.java:79)
        at okio.AsyncTimeout$1.write(AsyncTimeout.java:180)
        at okio.RealBufferedSink.flush(RealBufferedSink.java:224)
        at okhttp3.internal.http1.Http1Codec.finishRequest(Http1Codec.java:166)
        at okhttp3.internal.http.CallServerInterceptor.intercept(CallServerInterceptor.java:84)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:45)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at com.burgstaller.okhttp.AuthenticationCacheInterceptor.intercept(AuthenticationCacheInterceptor.java:50)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:254)
        at okhttp3.RealCall.execute(RealCall.java:92)
        at com.example.applicationpro.fragment.CurrentApplicationFragment.processFinish(CurrentApplicationFragment.java:119)
        at com.example.applicationpro.fragment.CurrentApplicationFragment$IOAsyncTask.onPostExecute(CurrentApplicationFragment.java:226)
        at com.example.applicationpro.fragment.CurrentApplicationFragment$IOAsyncTask.onPostExecute(CurrentApplicationFragment.java:140)
        at android.os.AsyncTask.finish(AsyncTask.java:660)
        at android.os.AsyncTask.-wrap1(AsyncTask.java)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:677)
        at android.os.Handler.dispatchMessage(Handler.java:110)
        at android.os.Looper.loop(Looper.java:203)
        at android.app.ActivityThread.main(ActivityThread.java:6361)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)

2 个答案:

答案 0 :(得分:0)

processFinish()方法下

您正在尝试通过以下行进行网络通话。

// CAN'T EXECUTE NEXT LINE

    mResponseBody = Objects.requireNonNull(mClient.newCall(mRequest).execute().body()).string();

processFinish()在UI线程上运行,不允许调用网络操作。仅在 doInBackground()方法中允许网络操作。

答案 1 :(得分:0)

在完成Asynctask之后,您就创建了一个调用函数的接口,将从UI线程中调用该函数。

但是在您的回调函数中,您将进行另一个引发异常的Networkcall,因为UI线程上禁止进行网络操作。您必须开始通话

mResponseBody = Objects.requireNonNull(mClient.newCall(mRequest).execute().Body()).string();

在另一个Asynctask中,并通过另一个回调接收mResponseBody。