Android - 片段未附加到活动

时间:2017-07-29 20:16:54

标签: java android android-fragments android-viewpager viewpagerindicator

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

  

“java.lang.IllegalStateException:Fragment ProductFragment {c46ba8a}未附加到活动”

代码如下: -

产品碎片:

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


}

我不知道我哪里错了。我搜索了错误,甚至尝试了以下链接的解决方案:
Fragment MyFragment not attached to Activity
我在SO上提问,但我没有得到答复/答案。可能是一个小错误,语法/格式问题,或一个重复的问题,但我的案件可能与其他案件不同。
所以请帮助和回应 谢谢。
- 编辑 -
HomeActivity:

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错误:

  

致命的例外:主要                                                                 过程:com.pisac.foodrestaurant,PID:29700                                                                 java.lang.IllegalStateException:片段ProductFragment {13525074}未附加到Activity                                                                     在android.app.Fragment.getResources(Fragment.java:800)                                                                     在com.pisac.foodrestaurant.ProductFragment.onPageSelected(ProductFragment.java:149)                                                                     在android.support.v4.view.ViewPager.dispatchOnPageSelected(ViewPager.java:1967)                                                                     在android.support.v4.view.ViewPager.scrollToItem(ViewPager.java:685)                                                                     在android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:669)                                                                     在android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:630)                                                                     在android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:622)                                                                     在com.pisac.foodrestaurant.ProductFragment $ 1.run(ProductFragment.java:244)                                                                     在android.os.Handler.handleCallback(Handler.java:739)                                                                     在android.os.Handler.dispatchMessage(Handler.java:95)                                                                     在android.os.Looper.loop(Looper.java:135)                                                                     在android.app.ActivityThread.main(ActivityThread.java:5910)                                                                     at java.lang.reflect.Method.invoke(Native Method)                                                                     在java.lang.reflect.Method.invoke(Method.java:372)                                                                     在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1405)                                                                     在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)

2 个答案:

答案 0 :(得分:2)

你的线路有问题

    pd.dismiss();

onPostExecute中的GetUrlData。把它放在if (isAdded ())里面根据您在问题中提到的问题的答案。您的对话框使用活动的上下文。

修改

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

答案 1 :(得分:1)

感谢您的帮助。
我得到了答案 我在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();
    }
}

再次感谢。