viewpager带有动态数据的IllegalStateException

时间:2017-05-19 09:06:20

标签: android android-viewpager

我正在从webservice动态创建tablayout标签。 tablayout附加到viewpager。当我在viewpager中滑动页面时,应用程序崩溃并出现IllegalStateException。我搜索了这个例外,发现它可能是由于片段造成的,所以我在一些SO帖子中建议使用getChildFragmentManager。我也使用v而不是FragmentPagerAdapter,但我仍然得到相同的错误。有什么我做错了,因为我在活动中使用了相同的代码并且工作正常。

FATAL EXCEPTION: main
                                                               Process: com.nits_35.wrd, PID: 5175
                                                               java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item count: 4, found: 15 Pager id: com.nits_35.wrd:id/category_viewpager Pager class: class cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager Problematic adapter: class com.nits_35.wrd.views.fragments.Frag_Seller_Market$SampleFragmentPagerAdapter
                                                                   at android.support.v4.view.ViewPager.populate(ViewPager.java:1167)
                                                                   at android.support.v4.view.ViewPager.populate(ViewPager.java:1116)
                                                                   at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1642)
                                                                   at android.view.View.layout(View.java:16924)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5602)
                                                                   at android.widget.LinearLayout.setChildFrame(LinearLayout.java:2001)
                                                                   at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1844)
                                                                   at android.widget.LinearLayout.onLayout(LinearLayout.java:1753)
                                                                   at android.view.View.layout(View.java:16953)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5602)
                                                                   at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:1193)
                                                                   at android.view.View.layout(View.java:16953)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5602)
                                                                   at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1189)
                                                                   at android.view.View.layout(View.java:16953)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5602)
                                                                   at android.widget.FrameLayout.layoutChildren(FrameLayout.java:396)
                                                                   at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
                                                                   at android.view.View.layout(View.java:16953)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5602)
                                                                   at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1189)
                                                                   at android.view.View.layout(View.java:16953)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5602)
                                                                   at android.widget.FrameLayout.layoutChildren(FrameLayout.java:396)
                                                                   at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
                                                                   at android.view.View.layout(View.java:16953)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5602)
                                                                   at android.widget.LinearLayout.setChildFrame(LinearLayout.java:2001)
                                                                   at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1844)
                                                                   at android.widget.LinearLayout.onLayout(LinearLayout.java:1753)
                                                                   at android.view.View.layout(View.java:16953)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5602)
                                                                   at android.widget.FrameLayout.layoutChildren(FrameLayout.java:396)
                                                                   at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
                                                                   at android.view.View.layout(View.java:16953)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5602)
                                                                   at android.widget.LinearLayout.setChildFrame(LinearLayout.java:2001)
                                                                   at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1844)
                                                                   at android.widget.LinearLayout.onLayout(LinearLayout.java:1753)
                                                                   at android.view.View.layout(View.java:16953)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5602)
                                                                   at android.widget.FrameLayout.layoutChildren(FrameLayout.java:396)
                                                                   at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
                                                                   at com.android.internal.policy.PhoneWindow$DecorView.onLayout(PhoneWindow.java:2722)
                                                                   at android.view.View.layout(View.java:16953)
                                                                   at android.view.ViewGroup.layout(ViewGroup.java:5602)
                                                                   at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2549)
                                                                   at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2252)
                                                                   at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1323)
                                                                   at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6706)
                                                                   at android.view.Choreographer$CallbackRecord.run(Choreographer.java:894)
                                                                   at android.view.Choreographer.doCallbacks(Choreographer.java:696)
                                                                   at android.view.Choreographer.doFrame(Choreographer.java:631)
                                                                   at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:880)
                                                                   at android.os.Handler.handleCallback(Handler.java:815)
                                                                   at android.os.Handler.dispatchMessage(Handler.java:104)
                                                                   at android.os.Looper.loop(Looper.java:207)
                                                                   at android.app.ActivityThread.main(ActivityThread.java:5728)
                                                               	at java.lang.reflect.Method.invok
public class Frag_Seller_Market extends Fragment {

    
    private AutoScrollViewPager category_viewpager;
    
    private SampleFragmentPagerAdapter adapter;

  

    public Frag_Seller_Market() {
        // Required empty public constructor
    }
    private TabLayout seller_tabs_store;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
       
        View v=inflater.inflate(R.layout.seller_fragment_market, container, false);
        seller_tabs_store=(TabLayout)v.findViewById(R.id.seller_tabs_store);
      
    
        category_viewpager=(AutoScrollViewPager) v.findViewById(R.id.category_viewpager);

        return v;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

       

        if (cd.isConnectingToInternet()){

             fetchCategoryList();
        }else {

            Toast.makeText(getActivity(),"No Internet",Toast.LENGTH_SHORT).show();
        }

    }

   
    private void fetchCategoryList(){
        if(arrayList!=null)arrayList.clear();
        pd.setMessage("loading...");
        pd.show();

        StringRequest stringRequest = new StringRequest(Request.Method.GET, Utility.CATEGORYLIST,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        pd.dismiss();
                        System.out.println("Category_List_Response"+response);


                        try {
                            JSONObject jObj = new JSONObject(response);
                            if(jObj.getInt("Ack")==1){
                                JSONArray jsonArray = jObj.getJSONArray("CategoryList");
                                for(int i=0;i<jsonArray.length();i++){
                                    JSONObject main = jsonArray.getJSONObject(i);

                                    Model market = new Model();
                                    market.setProduct_category_id(main.getString("id"));
                                    market.setProduct_category_name(main.getString("name"));
                                  

                                    arrayList.add(market);

                                }

                                if(getActivity()!=null)
                                category_viewpager.setAdapter(new SampleFragmentPagerAdapter(getChildFragmentManager(), getActivity(), arrayList));
                                seller_tabs_store.setupWithViewPager(category_viewpager);

                            }


                        } catch (JSONException e) {
                            // JSON error
                            System.out.println("jay_JSONError "+e);
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (error instanceof TimeoutError) {
                    Toast.makeText(getActivity(),getString(R.string.tooslow),Toast.LENGTH_LONG).show();
                }else if (error instanceof NoConnectionError){
                    Toast.makeText(getActivity(),getString(R.string.nointernet),Toast.LENGTH_LONG).show();
                }else if (error instanceof AuthFailureError) {
                    System.out.println("jay_AuthFailureError "+error);
                } else if (error instanceof ServerError) {
                    System.out.println("sammy_ServerError "+error);
                } else if (error instanceof NetworkError) {
                    System.out.println("sammy_NetworkError "+error);
                } else if (error instanceof ParseError) {
                    System.out.println("sammy_ParseError "+error);
                }
            }
        }) ;

        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        requestQueue.add(stringRequest);
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                10000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    }

    public class SampleFragmentPagerAdapter extends FragmentStatePagerAdapter {

        private Context context;
        private ArrayList<Model> arrayList;

        public SampleFragmentPagerAdapter(FragmentManager fm, Context context, ArrayList<Model> arrayList) {
            super(fm);
            this.context = context;
            this.arrayList=arrayList;
        }

        @Override
        public int getCount() {
            return arrayList.size();
        }

        @Override
        public Fragment getItem(int position) {
           return Frag_store_productwiselist.newInstance(arrayList.get(position).getProduct_category_id());

        }

        @Override
        public CharSequence getPageTitle(int position) {
            return arrayList.get(position).getProduct_category_name();
        }
    }

  
}

2 个答案:

答案 0 :(得分:0)

不是每次都创建一个新的适配器,您可以根据数据是否有任何变化通知它更新视图。

所以你可以做的是:

if(sampleFragmentPagerAdapter == null){
sampleFragmentPagerAdapter = new SampleFragmentPagerAdapter(getChildFragmentManager(), getActivity(), arrayList);
}else{
sampleFragmentPagerAdapter.notifyDataSetChanged();
}
category_viewpager.setAdapter(sampleFragmentPagerAdapter);                                
seller_tabs_store.setupWithViewPager(category_viewpager);

制作sampleFragmentPagerAdapter,它是活动或片段中的全局对象。

答案 1 :(得分:0)

查看错误消息:

  

应用程序的PagerAdapter在不调用PagerAdapter#notifyDataSetChanged的情况下更改了适配器的内容!预期的适配器项目数:4,找到:15

问题来自getCount中的PagerAdapter功能:

    @Override
    public int getCount() {
        return arrayList.size();
    }

通过此功能,每当add/remove/clear arrayList viewPagerAdapter.notifyDataSetChanged()时,您都需要致电getItemPosition

P / s:您需要覆盖Adapter的{​​{1}}功能才能使其正常工作。

@Override
public int getItemPosition(Object object) {
    // Causes adapter to reload all Fragments when
    // notifyDataSetChanged is called
    return POSITION_NONE;
}