Android - 片段未附加到 activity

Android - Fragment not attached to activity

我有一个 activity 可以加载一个片段,但是当我按下片段上的后退按钮时它显示错误 :-

"java.lang.IllegalStateException: Fragment ProductFragment{c46ba8a} not attached to Activity"

代码如下:-

产品片段:

public class ProductFragment extends Fragment implements TabLayout.OnTabSelectedListener, ViewPager.OnPageChangeListener {
    private static final String PRODUCT_DATA = "product_data";
    private TabLayout tabLayout;
    private ViewPager viewPager;
    NestedScrollView nestedScrollView;

    //RecyclerView listView;
    //ImageView ivHeader;
    ProgressDialog pd;
    Bundle bundle;
    ViewPager viewPager1;
    private LinearLayout pager_indicator;
    public String DATA = "data";
    public String PRODUCTS = "products";
    //public String SPRODUCTS = "sproducts";
    public String ID = "id";
    public String NAME = "productName";
    public String IMAGEURL = "productImg1";
    public String DESCRIPTION = "description";
    public String PRICE = "price";
    public String DELIVERYTYPE = "deliverytype";
    //String url = "https://chiraggohil.000webhostapp.com/product.php";
    String url = "http://www.thinkdream.in/lunchbox2/product_api/getProductList";
    String sliderImageUrl = "http://www.thinkdream.in/lunchbox2/assets/images/product/2.png";

    ArrayList<Product> list = new ArrayList<>();
    ArrayList<Product> sliderImagesList = new ArrayList<>();
    private int dotsCount = 0;
    private ImageView[] dots;
    private static int CURRENT_PAGE = 0;
    ViewPagerSliderAdapter viewPagerSliderAdapter;

    ConnectivityManager cm;
    NetworkInfo activeNetwork;
    boolean isConnected;

    //private boolean load = false;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View v = inflater.inflate(R.layout.fragment_product, container, false);
        viewPager1 = (ViewPager) v.findViewById(R.id.viewpager);
        //listView = (RecyclerView) v.findViewById(R.id.gvProducts);
        nestedScrollView = (NestedScrollView) v.findViewById(R.id.nestedSV);
        pager_indicator = (LinearLayout) v.findViewById(R.id.viewPagerCountDots);

        //nestedScrollView.setFillViewport(true);
        //ivHeader = (ImageView) v.findViewById(R.id.ivHeader);
        bundle = new Bundle();
        tabLayout = (TabLayout) v.findViewById(R.id.tabLayout);
        viewPager = (ViewPager) v.findViewById(R.id.pager);

        viewPagerSliderAdapter = new ViewPagerSliderAdapter(getActivity(), sliderImagesList);

        cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        activeNetwork = cm.getActiveNetworkInfo();
        isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

        if (savedInstanceState != null) {
            sliderImagesList = savedInstanceState.getParcelableArrayList(PRODUCT_DATA);
            viewPager1.setAdapter(viewPagerSliderAdapter);
            viewPagerSliderAdapter.notifyDataSetChanged();
        } else {
            if (isConnected) {
                new GetUrlData(getActivity()).execute();
            } else {
                Toast.makeText(getActivity(), "You are not connected to the internet!", Toast.LENGTH_SHORT).show();
            }
        }

        tabLayout.addTab(tabLayout.newTab().setText("Pizza"));
        tabLayout.addTab(tabLayout.newTab().setText("Sandwich"));
        tabLayout.addTab(tabLayout.newTab().setText("Burger"));
        Pager adapter = new Pager(getChildFragmentManager(), tabLayout.getTabCount());
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.addOnTabSelectedListener(this);

        viewPager1.addOnPageChangeListener(this);
        return v;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelableArrayList(PRODUCT_DATA, sliderImagesList);
    }

    @Override
    public void onResume() {
        super.onResume();
        pager_indicator.removeAllViews();
        //Picasso.with(getActivity()).load(sliderImageUrl).into(ivHeader);
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        viewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        for (int i = 0; i < dotsCount; i++) {
            dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
        }
        if (position >= dotsCount) {
            dots[0].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
        } else {
            dots[position].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private class GetUrlData extends AsyncTask<Void, Void, Void> {

        GetUrlData(Context context) {
            pd = new MyCustomProgressDialog(context, R.style.NewDialog);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd.setCancelable(false);
            pd.show();
        }

        @Override
        protected Void doInBackground(Void... voids) {
            ServiceHandler sh = new ServiceHandler();
            String result = sh.Getdata(url);
            //list.clear();
            sliderImagesList.clear();

            if (result != null) {
                try {
                    list.clear();
                    JSONObject jsonObject = new JSONObject(result);
                    JSONArray jsonArray = jsonObject.getJSONArray(DATA);

                    //JSONArray jsonArray = jsonObject1.getJSONArray(PRODUCTS);

                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject2 = jsonArray.getJSONObject(i);
                        String id = jsonObject2.getString(ID);
                        String name = jsonObject2.getString(NAME);
                        String imgpath = jsonObject2.getString(IMAGEURL);
                        String desc = jsonObject2.getString(DESCRIPTION);
                        String price = jsonObject2.getString(PRICE);
                        //String deliverytype = jsonObject2.getString(DELIVERYTYPE);

                        Product product = new Product();
                        product.setId(id);
                        product.setProductName(name);
                        product.setProductImage(imgpath);
                        product.setProductDescription(desc);
                        product.setProductPrice(price);
                        //list.add(product);
                        sliderImagesList.add(product);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            pd.dismiss();
            // Picasso.with(getActivity()).load(sliderImageUrl).into(ivHeader);
            if(isAdded()) {
            viewPagerSliderAdapter = new ViewPagerSliderAdapter(getActivity(), sliderImagesList);
            Log.e("slider",sliderImagesList.toString());
            viewPager1.setAdapter(viewPagerSliderAdapter);
            viewPagerSliderAdapter.notifyDataSetChanged();
            slider();
            setUiPageViewController();
            }else {
                Log.e("not added","not added");
            }
        }

    }

    private void slider() {
        int NUM_PAGES = sliderImagesList.size();
        final android.os.Handler handler = new android.os.Handler();
        final Runnable runnable = new Runnable() {
            @Override
            public void run() {
                CURRENT_PAGE = viewPager1.getCurrentItem();
                if (CURRENT_PAGE == 2) {
                    CURRENT_PAGE = -1;
                }
                viewPager1.setCurrentItem(CURRENT_PAGE + 1, true);
            }
        };
        Timer swipeTimer = new Timer();
        swipeTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.post(runnable);
            }
        }, 100, 4000);
    }

    private void setUiPageViewController() {
        dotsCount = 3;
        dots = new ImageView[dotsCount];

        for (int i = 0; i < dotsCount; i++) {
            dots[i] = new ImageView(getActivity());
            dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
            );

            params.setMargins(4, 0, 4, 0);

            pager_indicator.addView(dots[i], params);
        }
        dots[0].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
    }


}

我不知道我哪里错了。我已经搜索了错误,甚至尝试了下面 link 中的解决方案:
Fragment MyFragment not attached to Activity
我在 SO 上提问,但没有得到 response/answers。可能存在小错误、grammatical/formating 问题或重复问题,但我的情况可能与其他情况不同。
所以请帮助和回应。
谢谢。
--已编辑--
主页活动:

public class HomeActivity extends AppCompatActivity implements View.OnClickListener {
    DrawerLayout drawerLayout;
    NavigationView navigationView;
    Toolbar toolbar;
    TextView tvActionTitle;
    SessionManager sessionManager;
    GPSTracker gps;
    int i = 0;
    private FrameLayout redCircle;
    private TextView countTextView;
    int cartcount = 0;
    Menu menu;
    LunchBoxDB lunchBoxDB;
    private String uid;
    SharedPreferences pref;
    private int totalquantity = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        navigationView = (NavigationView) findViewById(R.id.navigation);
        tvActionTitle = (TextView) findViewById(R.id.tvActionTitle);

        Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/Quicksand_Bold_Oblique.otf");
        tvActionTitle.setTypeface(custom_font);

        setSupportActionBar(toolbar);
        //getSupportActionBar().setDisplayShowTitleEnabled(false);
        lunchBoxDB = new LunchBoxDB(this);
        pref = getSharedPreferences("loginPref", Context.MODE_PRIVATE);
        uid = pref.getString("id", null);

        ProductFragment pf = new ProductFragment();
        getFragmentManager().beginTransaction().replace(R.id.content_frame, pf).commit();

        sessionManager = new SessionManager(this);
        toolbar.setNavigationIcon(R.mipmap.ic_menu_white_24dp);
        toolbar.setNavigationOnClickListener(this);

        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem item) {
                Fragment frag = null;
                int itemId = item.getItemId();
                if (itemId == R.id.nav_home) {
                    drawerLayout.closeDrawers();
                    Intent i = new Intent(HomeActivity.this, HomeActivity.class);
                    startActivity(i);
                    HomeActivity.this.finish();
                } else if (itemId == R.id.nav_profile) {
                    frag = new AccountFragment();
                    getFragmentManager().beginTransaction().replace(R.id.content_frame, frag).addToBackStack("Account").commit();
                    drawerLayout.closeDrawers();
                } else if (itemId == R.id.nav_order) {
                    drawerLayout.closeDrawers();
                    OrdersFragment of = new OrdersFragment();
                    getFragmentManager().beginTransaction().replace(R.id.content_frame, of).addToBackStack("Orders").commit();
                } else if (itemId == R.id.nav_store_locator) {
                    Intent i = new Intent(HomeActivity.this, LocationActivity.class);
                    startActivity(i);
                    drawerLayout.closeDrawers();
                } else if (itemId == R.id.nav_logout) {
                    drawerLayout.closeDrawers();
                    sessionManager.logoutUser();
                } else if (itemId == R.id.nav_help) {
                    drawerLayout.closeDrawers();
                    Intent i = new Intent(Intent.ACTION_DIAL);
                    i.setData(Uri.parse("tel:+918460765785"));
                    startActivity(i);
                } else if (itemId == R.id.nav_corpinquiry) {
                    drawerLayout.closeDrawers();
                    CorpInquiryFragment crpf = new CorpInquiryFragment();
                    getFragmentManager().beginTransaction().replace(R.id.content_frame, crpf).addToBackStack("CorpInquiry").commit();
                }
                return false;
            }
        });

    }

    private void setNavigationDrawer() {
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.closeDrawer(GravityCompat.START);
        } else {
            drawerLayout.openDrawer(GravityCompat.START);

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.nav_drawer, menu);
        final MenuItem alertMenuItem = menu.findItem(R.id.shopping_bag);
        FrameLayout rootView = (FrameLayout) alertMenuItem.getActionView();

        redCircle = (FrameLayout) rootView.findViewById(R.id.view_alert_red_circle);
        countTextView = (TextView) rootView.findViewById(R.id.view_alert_count_textview);

        rootView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onOptionsItemSelected(alertMenuItem);
            }
        });
        badgeupdate();
        return super.onCreateOptionsMenu(menu);
    }

    void badgeupdate() {
        SQLiteDatabase db = lunchBoxDB.getReadableDatabase();
        String query = "select sum(quantity) from cart where uid = " + uid;
        Cursor c = db.rawQuery(query, null);
        if (c != null && c.moveToFirst()) {
            totalquantity = c.getInt(0);
        }
        c.close();
        cartcount = totalquantity;
        countTextView.setText(String.valueOf(cartcount));
        redCircle.setVisibility((cartcount > 0) ? VISIBLE : GONE);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.shopping_bag) {
            SharedPreferences pref = this.getSharedPreferences("couponPref", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = pref.edit();
            editor.putString("discount", null);
            editor.apply();
            CartFragment cf = new CartFragment();
            getFragmentManager().beginTransaction().replace(R.id.content_frame, cf, "CartFragment").addToBackStack(null).commit();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.closeDrawer(GravityCompat.START);
        }/*else if(i==0){
            Toast.makeText(this, "Press back again to exit!", Toast.LENGTH_SHORT).show();
            i=1;
        }*/ else {
            //i=0;
            super.onBackPressed();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        gps = new GPSTracker(this);
    }

    @Override
    public void onClick(View view) {
        setNavigationDrawer();
    }
}

Logcat 错误:

FATAL EXCEPTION: main Process: com.pisac.foodrestaurant, PID: 29700 java.lang.IllegalStateException: Fragment ProductFragment{13525074} not attached to Activity at android.app.Fragment.getResources(Fragment.java:800) at com.pisac.foodrestaurant.ProductFragment.onPageSelected(ProductFragment.java:149) at android.support.v4.view.ViewPager.dispatchOnPageSelected(ViewPager.java:1967) at android.support.v4.view.ViewPager.scrollToItem(ViewPager.java:685) at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:669) at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:630) at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:622) at com.pisac.foodrestaurant.ProductFragment.run(ProductFragment.java:244) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5910) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)

你的线路有问题

    pd.dismiss();

在您的 GetUrlDataonPostExecute 中。根据您在问题中提到的问题的答案,将其放入 if (isAdded ()) 内。您的对话使用 activity.

的上下文

编辑

onPageSelected 方法中添加一个 if 块来检查 Fragment 是否已附加,即

@Override
public void onPageSelected(int position) {
    if(!isAdded ())
         return;

    for (int i = 0; i < dotsCount; i++) {
        dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
    }
    if (position >= dotsCount) {
        dots[0].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
    } else {
        dots[position].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
    }
}

谢谢你的帮助。
我得到了答案。
我在 ProductFragment 代码中添加了 onStop,如下所示:

@Override
public void onStop() {
    viewPager1.setAdapter(null);
    super.onStop();
}  

并更新 onResume :

@Override
public void onResume() {
    super.onResume();
    pager_indicator.removeAllViews();
    if(viewPagerSliderAdapter==null){
        new GetUrlData(getActivity()).execute();
    }
}

再次感谢。