IllegalStateException с PagerAdapter

Я получаю исключение IllegalStateException в этом действии, но не совсем уверен, что происходит. Вот класс ViewPagerAdapter в QuickContactActivity.

private class ViewPagerAdapter extends FragmentPagerAdapter {
    public ViewPagerAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
    }

    @Override
    public Fragment getItem(int position) {
        QuickContactListFragment fragment = new QuickContactListFragment();
        final String mimeType = mSortedActionMimeTypes.get(position);
        final List<Action> actions = mActions.get(mimeType);
        fragment.setActions(actions);
        return fragment;
    }

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

Вот журнал сбоев:

07-15 09:49:21.060: E/com.##.##.##.Application(12378): Thread uncaught exception:
07-15 09:49:21.060: E/com.##.##.##.Application(12378): java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item count: 0, found: 1 Pager id: com.##.##.android:id/item_list_pager Pager class: class android.support.v4.view.ViewPager Problematic adapter: class com.##.contacts.quickcontact.QuickContactActivity$ViewPagerAdapter
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.support.v4.view.ViewPager.populate(ViewPager.java:959)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.support.v4.view.ViewPager.populate(ViewPager.java:911)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1432)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.view.View.measure(View.java:15518)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.view.View.measure(View.java:15518)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.view.View.measure(View.java:15518)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.view.View.measure(View.java:15518)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.view.View.measure(View.java:15518)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2176)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.view.View.measure(View.java:15518)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1874)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1089)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1265)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.view.Choreographer.doCallbacks(Choreographer.java:562)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.view.Choreographer.doFrame(Choreographer.java:532)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.os.Handler.handleCallback(Handler.java:725)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.os.Handler.dispatchMessage(Handler.java:92)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.os.Looper.loop(Looper.java:137)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at android.app.ActivityThread.main(ActivityThread.java:5041)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at java.lang.reflect.Method.invokeNative(Native Method)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at java.lang.reflect.Method.invoke(Method.java:511)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-15 09:49:21.060: E/com.##.##.##.Application(12378):  at dalvik.system.NativeStart.main(Native Method)
07-15 09:49:21.060: E/ACRA(12378): ACRA caught a IllegalStateException exception for com.##.##.android. Building report.

person thisiscrazy4    schedule 16.07.2013    source источник
comment
вызывать notifyDataSetChanged() на адаптере каждый раз при изменении размера данных.   -  person Raghunandan    schedule 16.07.2013
comment
@Raghunandan: где мне использовать метод notifyDataSetChanged()?   -  person Akarsh M    schedule 22.07.2013
comment
Найдите одну возможную причину, которую я объяснил здесь: «Исключение java lang нелегальное состояние в окне просмотра после обновления данных»> stackoverflow.com/questions/35260951/   -  person carl    schedule 23.07.2019


Ответы (3)


Проблема в том, что ваш список элементов/страниц для отображения в PageAdapter меняется, и вы не вызываете pageAdapter.notifyDataSetChanged().

Если вы продолжите читать сообщение, то говорит, что ждете 0 элементов и получаете 1. При этом кажется, что вы устанавливаете адаптер до того, как устанавливаете все элементы/страницы, которые получает адаптер.

person Aracem    schedule 16.07.2013
comment
где мы должны использовать метод notifyDataSetChanged()? - person Akarsh M; 22.07.2013
comment
Когда размер данных изменился. В первый раз вы НЕ должны называть это, конечно. - person Aracem; 22.07.2013
comment
вы видите этот пост: stackoverflow.com/questions/17784476/ - person Akarsh M; 22.07.2013
comment
после того, как вы измените элементы адаптера, вы можете вызвать notifyDataSetChanged() - person savepopulation; 06.10.2015

У меня такие же проблемы, как и у вас, у меня есть viewpager в Activity A, затем, когда пользователь щелкнул элемент в viewpager, он перейдет к Activity B, у которого тоже есть viewpager. После того, как пользователь вернется из Activity B в Activity A, он выдаст Exception следующим образом:

java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item count: 4, found: 0 Pager id: com.gbu.app.templateforbussiness:id/header_view_pager_list Pager class: class android.support.v4.view.ViewPager Problematic adapter: class com.gbu.app.templateforbussiness.adapter.DetailProductPagerAdapter

Я думаю, проблема в том, что содержимое данных, которое адаптер просмотра пейджера всегда имеет 0, потому что у адаптера нет данных, которые прошли через Activity. Итак, я попробовал работать, как в этом примере:

DetailProductActivity.class

public class DetailProductActivity extends FragmentActivity {
    private ViewPager product_detail_viewpager;
    private DetailProductPagerAdapter detail_product_adapter;
    private Intent product_detail_intent;
    public static List<Product> detail_product;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail_product);
        product_detail_viewpager = (ViewPager) findViewById(R.id.detail_product_viewpager);
        detail_product = HomeActivity.home_product;
    }

    @Override
    protected void onStart() {
        super.onStart();
        product_detail_intent = getIntent();
        startApp(product_detail_intent);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void startApp(Intent data) {
        // TODO Auto-generated method stub
            // pass the Array, List of data to viewpager adapter like this
        detail_product_adapter = new DetailProductPagerAdapter(getSupportFragmentManager(), detail_product); 
        product_detail_viewpager.setAdapter(detail_product_adapter);
        product_detail_viewpager.setCurrentItem(data.getIntExtra("current_item", 0));
    }

}

И адаптер viewpager: DetailProductPagerAdapter.class

public class DetailProductPagerAdapter extends FragmentPagerAdapter {
    private ProductDetailFragment detail_product_fragment;
    private Bundle data;
    private List<Product> detail_product;

    // the data from Activity passed to this adapter        
    public DetailProductPagerAdapter(FragmentManager fm, List<Product> p) {
        super(fm);
        // TODO Auto-generated constructor stub
        detail_product = p;
    }

    // then passing the data again to your fragment class, like this example
    @Override
    public Fragment getItem(int arg0) {
        // TODO Auto-generated method stub
        detail_product_fragment = new ProductDetailFragment(detail_product);
        data = new Bundle();
        data.putInt("current_item", arg0);
        detail_product_fragment.setArguments(data);
        return detail_product_fragment;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return detail_product.size();
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }   

}

И класс фрагмента: ProductDetailFragment.class

@SuppressLint("ValidFragment")
public class ProductDetailFragment extends Fragment {
    private RelativeLayout detail_item_header;
    private ImageView detail_item_imv;
    private TextView detail_item_tv_title;
    private WebView detail_item_web_content;
    private DisplayMetrics detail_metrics;
    private List<Product> detail_product;
    private int index_item;

    // the data from adapter pass it to this fragment
    public ProductDetailFragment(List<Product> p) {
        detail_product = p;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View view_detail = inflater.inflate(R.layout.item_product_detail_viewpager, container, false);
        detail_metrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(detail_metrics);
        savedInstanceState = getArguments();
        index_item = savedInstanceState.getInt("current_item");
        detail_item_header = (RelativeLayout) view_detail.findViewById(R.id.item_header_product_viewpager);
        detail_item_imv = (ImageView) detail_item_header.findViewById(R.id.item_imv_product_viewpager);
        detail_item_tv_title = (TextView) detail_item_header.findViewById(R.id.item_tv_title_product_viewpager);
        detail_item_web_content = (WebView) view_detail.findViewById(R.id.item_web_product_viewpager);
        startApp();
        return view_detail;
    }

    private void startApp() {
        // TODO Auto-generated method stub
        detail_item_header.getLayoutParams().height = (int) (detail_metrics.heightPixels * 0.38);
        if (detail_product.get(index_item).getStatus() == 0) {
            new loadImageProduct(detail_item_imv).execute(detail_product.get(index_item).getImage());
        }else {
            detail_item_imv.setImageBitmap(detail_product.get(index_item).getBmp());
        }
        detail_item_tv_title.setText(detail_product.get(index_item).getTitle());
        String web_content_product = "<!DOCTYPE html>"+
                                     "<html>"+
                                     "<body>"+
                                     "<p>Harga : "+detail_product.get(index_item).getPrice()+"</p><br>"+
                                     detail_product.get(index_item).getDetail()+"<br><br>"+
                                     detail_product.get(index_item).getDetail2()+
                                     "</body>"+
                                     "</html>";
        detail_item_web_content.loadDataWithBaseURL("https://www.google.com", web_content_product, "text/html", "UTF-8", null);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private class loadImageProduct extends AsyncTask<String, Integer, Bitmap> {
        private Bitmap b;
        private ImageView vimv;
        private GetImage get_image;

        public loadImageProduct(ImageView v) {
            vimv = v;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            b = null;
            get_image = new GetImage();
        }

        @Override
        protected Bitmap doInBackground(String...url) {
            try {
                b = get_image.loadImageFromServer(url[0]);
                if (b != null)
                    return b;
            } catch(OutOfMemoryError e) {

            }
            return b;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            if (result != null) {
                detail_product.get(index_item).setBmp(result);
                detail_product.get(index_item).setStatus(1);
                vimv.setImageBitmap(result);
            }
        }
    }

}

Теперь исключение перед ним больше не будет отображаться, и просмотрщик работает нормально. Этот метод пытается сделать viewpager таким же, как listview, потому что listview будет передавать данные через адаптер, поэтому адаптер не потеряет содержимое данных, даже если данные изменились. Я надеюсь, что этот пример поможет вашим проблемам. Ваше здоровье.

person Aprido Sandyasa    schedule 31.01.2014

Это случилось со мной, когда я попытался переопределить getCount() адаптера страницы.

При авторизации у меня показывается только одна страница. После окончания авторизации я меняю количество страниц на 3. У меня падает, если я не вызываю InvalidatePageAdapter() один раз

@Override
public int getCount() {

    if (mAuthorization_Status == AUTH_STATUS.AUTH_SUCCESS) {

        if (!isRefreshed) {
            isRefreshed = true;
            this.notifyDataSetChanged();
        }

        return NUM_PAGES;

    } else {

        return 1;
        //return NUM_PAGES;

    }

} // END: getCount
person Yury Finchenko    schedule 30.03.2016