Android Fragments Android -片段未附加到Activity

0vvn1miw  于 2023-10-19  发布在  Android
关注(0)|答案(2)|浏览(124)

我有一个加载片段的活动,但当我按下片段上的返回按钮时,它显示错误:
"java. lang. IllegalStateException:片段ProductFragment {c46ba8a}未附加到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));
    }

}

我不知道我错在哪里。我已经搜索了错误,甚至尝试了下面链接的解决方案:
Fragment MyFragment not attached to Activity
我在SO上提出问题,但我没有得到回应/答案。可能有一个小错误,语法/格式问题,或重复的问题,但有一个可能性,我的情况是不同的,然后其他人。
请帮助和回应。
谢谢.

  • --编辑--*
    • 首页活动:**
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.皮萨克. foodresistant,PID:29700 java. lang. IllegalStateException:Fragment ProductFragment {13525074}未附加到Android上的Activity。应用程序片段。getResources(Fragment.java:800)at com.皮萨克。美食家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.皮萨克。美食家ProductFragment $www.example.com(ProductFragment.java:244)at android.骨密度在android上调用(Handler.java:739)。骨密度android上的dispatchMessage(Handler.java:95)。os. Looper. loop(Looper.java:135)at android. app. ActivityThread. main(ActivityThread.java:5910)在java中。lang。反思。方法。在java中调用(原生方法)。lang。反思。方法。在com上调用(Method.java:372)。机器人内部的操作系统ZygoteInit $1.run

polhcujo

polhcujo1#

你的线路有问题

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

kq0g1dla2#

谢谢你帮我
我知道答案了。
我在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();
    }
}

再次感谢。

相关问题