在完成 post 执行之前切换到另一个片段时,应用程序崩溃,并显示此错误

when switch to another fragment before completing the post execute the app gets crashed ,and show this error

class GetDashboardContentsAysnc 扩展 AsyncTask {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            shimmerFrameLayout.startShimmer();
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            shimmerFrameLayout.stopShimmer();
            shimmerFrameLayout.setVisibility(View.GONE);
                if(s!=null ) {
                    try {
                        JSONObject jsonObj = new JSONObject(s);
                        response = jsonObj.getString("response");
                        if (response.contains("success")) {

                            listcategories.clear();
                            JSONArray jsonArr = jsonObj.getJSONArray("catgories");
                            for (int i = 0; i < jsonArr.length(); i++) {
                                JSONObject userdata = jsonArr.getJSONObject(i);
                                String category_id = userdata.getString("category_id");
                                String category_name_english = userdata.getString("category_name_english");
                                String app_image = url1 + userdata.getString("app_image");

                                HashMap<String, String> news = new HashMap<>();
                                news.put("category_id", category_id);
                                news.put("category_name_english", category_name_english);
                                news.put("app_image", app_image);

                                listcategories.add(news);

                                Gson gson = new Gson();
                                List<HashMap<String, String>> textList = new ArrayList<>();
                                textList.addAll(listcategories);
                                String jsonText = gson.toJson(textList);
                                session.createdbcategoryesession(jsonText);

                            }


                            JSONArray jsonArr1 = jsonObj.getJSONArray("slider");

                            for (int i = 0; i < jsonArr1.length(); i++) {
                                JSONObject userdata = jsonArr1.getJSONObject(i);
                                String slider_id = userdata.getString("slider_id");
                                String mobile_banner = url + userdata.getString("mobile_banner");
                                ;
                                String slider_url = userdata.getString("slider_url");
                                ;
                                HashMap<String, String> news = new HashMap<>();
                                news.put("slider_id", slider_id);
                                news.put("mobile_banner", mobile_banner);
                                news.put("slider_url", slider_url);
                                listslider.add(news);


                            }


                            listrecipe.clear();
                            JSONArray jsonArr2 = jsonObj.getJSONArray("popular_receipe");

                            for (int i = 0; i < jsonArr2.length(); i++) {
                                JSONObject userdata = jsonArr2.getJSONObject(i);
                                String recipe_id = userdata.getString("recipe_id");
                                String recipe_title = userdata.getString("recipe_title");
                                ;
                                String rating = userdata.getString("rating");
                                String recipe_veg_status = userdata.getString("recipe_veg_status");
                                String image1 = url2 + userdata.getString("image1");

                                HashMap<String, String> news = new HashMap<>();
                                news.put("recipe_id", recipe_id);
                                news.put("recipe_title", recipe_title);
                                news.put("rating", rating);
                                news.put("recipe_veg_status", recipe_veg_status);
                                news.put("image1", image1);
                                listrecipe.add(news);

                                Gson gson = new Gson();
                                List<HashMap<String, String>> textList = new ArrayList<>();
                                textList.addAll(listrecipe);
                                String jsonText = gson.toJson(textList);
                                session.createdbpopularecipesesession(jsonText);


                            }


                            listlatestrecipe.clear();

                            JSONArray jsonArr4 = jsonObj.getJSONArray("latest_recipe");
                            for (int i = 0; i < jsonArr4.length(); i++) {

                                JSONObject userdata = jsonArr4.getJSONObject(i);
                                String recipe_id = userdata.getString("recipe_id");
                                String recipe_title = userdata.getString("recipe_title");
                                ;
                                String rating = userdata.getString("rating");
                                String recipe_veg_status = userdata.getString("recipe_veg_status");
                                String image1 = url2 + userdata.getString("image1");

                                HashMap<String, String> news = new HashMap<>();
                                news.put("recipe_id", recipe_id);
                                news.put("recipe_title", recipe_title);
                                news.put("rating", rating);
                                news.put("recipe_veg_status", recipe_veg_status);
                                news.put("image1", image1);
                                listlatestrecipe.add(news);

                                Gson gson = new Gson();
                                List<HashMap<String, String>> textList = new ArrayList<>();
                                textList.addAll(listlatestrecipe);
                                String jsonText = gson.toJson(textList);
                                session.createdblatestecipesesession(jsonText);
                            }

                        }


                        JSONArray jsonArr3 = jsonObj.getJSONArray("banner");
                        for (int i = 0; i < jsonArr3.length(); i++) {
                            JSONObject userdata = jsonArr3.getJSONObject(i);
                            String section_id = userdata.getString("section_id");
                            String section_image = url4 + userdata.getString("section_image");
                            ;
                            String sectionimage_url_website = userdata.getString("sectionimage_url_website");
                            ;

                            HashMap<String, String> news = new HashMap<>();
                            news.put("section_id", section_id);
                            news.put("section_image", section_image);
                            news.put("sectionimage_url_website", sectionimage_url_website);
                            listbanner.add(news);


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

                }




            lay_slider.setVisibility(View.VISIBLE);
            mPager.setAdapter(new ViewPagerAdaper(getActivity(),listslider));
            indicator.setViewPager(mPager);
            NUM_PAGES =listslider.size();
            final Handler handler = new Handler();
            final Runnable Update = new Runnable() {
                public void run() {
                    if (currentPage == NUM_PAGES)
                    {
                        currentPage = 0;
                    }
                    mPager.setCurrentItem(currentPage++, true);
                }
            };
            Timer swipeTimer = new Timer();
            swipeTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    handler.post(Update);
                }
            }, 3000, 3000);



            lay_slider1.setVisibility(View.VISIBLE);
            mPager1.setAdapter(new ViewPagerAdaper1(getActivity(),listbanner));
            indicator1.setViewPager(mPager1);
            NUM_PAGES1 =listbanner.size();
            final Handler handler1 = new Handler();
            final Runnable Update1 = new Runnable() {
                public void run() {
                    if (currentPage1 == NUM_PAGES1) {
                        currentPage1 = 0;
                    }
                    mPager1.setCurrentItem(currentPage1++, true);
                }
            };
            Timer swipeTimer1 = new Timer();
            swipeTimer1.schedule(new TimerTask() {
                @Override
                public void run() {
                    handler1.post(Update1);
                }
            }, 3000, 3000);




        }

        RequestHandler requestHandler=new RequestHandler();
        @Override
        protected String doInBackground(String... strings) {
            HashMap<String, String> data = new HashMap<String, String>();
            data.put("customer_id",customer_id);
            data.put("type","2");
            String result = requestHandler.sendPostRequest(getResources().getString(R.string.url_dashboard),data);
            return result;
        }
    }
    GetDashboardContentsAysnc getDashboardContentsAysnc=new GetDashboardContentsAysnc();
    getDashboardContentsAysnc.execute();

E/AndroidRuntime:致命异常:AsyncTask #4 java.lang.RuntimeException: 执行 doInBackground() 时出错 在 android.os.AsyncTask$3.done(AsyncTask.java:354) 在 java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383) 在 java.util.concurrent.FutureTask.setException(FutureTask.java:252) 在 java.util.concurrent.FutureTask.run(FutureTask.java:271) 在 android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245) 在 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 在 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 在 java.lang.Thread.run(Thread.java:764) 由以下原因引起:java.lang.IllegalStateException:片段 HomeFragment{c8446f (3220b686-b1ad-479f-ba62-1f4da23bc80a)} 未附加到上下文。 在 androidx.fragment.app.Fragment.requireContext(Fragment.java:774) 在 androidx.fragment.app.Fragment.getResources(Fragment.java:838) 在 .fragments.HomeFragment$1GetDashboardContentsAysnc.doInBackground(首页Fragment.java:480) 在.fragments.HomeFragment$1GetDashboardContentsAysnc.doInBackground(首页Fragment.java:272) 在 android.os.AsyncTask$2.call(AsyncTask.java:333) 在 java.util.concurrent.FutureTask.run(FutureTask.java:266) 在 android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245) 在 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 在 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 在 java.lang.Thread.run(Thread.java:764)

发生这种情况是因为 AsyncTask 正在尝试更新 UI,而当前 Fragment/Activity 已在后台消失。这是必然发生的。 为避免这种情况,您可以在 Asynctask.

postExecute 方法中检查当前 activity/fragment 是否可见

如上面的答案所述,它是片段可见性问题。

String result = requestHandler
              .sendPostRequest(getResources().getString(R.string.url_dashboard),data);

如果您在片段 class 中定义了 AsyncTask 并且如果在调用 getResources() 方法时片段未附加,则会导致应用程序崩溃.在这种情况下,getResources() 方法会导致问题。

考虑进行可见性检查,

String result = "";
if(isVisible())
{
   result = requestHandler
              .sendPostRequest(getResources()
                               .getString(R.string.url_dashboard),data);
}
return result;

这应该可以解决问题,否则就不要使用上下文提供的任何方法,例如 getResouces() 而是使用静态变量或直接使用 URL 字符串。

String result = requestHandler
              .sendPostRequest("http://api_url_here",data);

希望这能解决您的问题。 此致,