Search code examples
androidandroid-viewpagertextviewillegalstateexceptionandroid-pageradapter

Strange IllegalStateException with ViewPager and TextView


I have a strange crash on my app.

On my layout, I have a TextView independent of my viewPager, which is with the property android:layout_below, so, the TextView's parent is a RelativeLayout with ID rl, and ViewPager as well:

enter image description here

Now, when I change the adapter of my ViewPager, I'm changing the TextView's text at the same time, and I get the following IllegalStateException:

    ChiamataPOST chiamata = new ChiamataPOST(WSEntity); // My AsyncTask
    chiamata.execute(WS); // I execute it

    cittaSceltaTV.setText("whatever text"); // and I change my textView, I've tried to do it before and after the AsyncTask.

java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item count: 4, found: 0

but if I comment the TextView's setText()'s function, it works perfectly.

Is that strange? am I wrong?

Thanks in advance.


Solution

  • Call notifyDataSetChanged() on your PageAdapter before calling the setText() on your text view. like below

    notifyDataSetChanged();
    cittaSceltaTV.setText("whatever text"); 
    

    I believe as soon as you call the call the setText(), it's trying to update the list and it throws the IllegalStateException because it notices a discrepancy between the expected item count and the actual one. see below.

     Expected adapter item count: 4, found: 0