Reputation: 37627
I have a ViewPager with a PagerTitleStrip which paints fragments. Each fragment has a StableArrayAdapter which fill the fragment with information.
After an orientation change, when I click on the fragments, I'm getting a crash: java.lang.IndexOutOfBoundsException: Index: 8, Size: 7
When the orientation change is produced, I can see the same fragment page as before the orientation change. But if I click on it, it produces the crash because probably the viewpager has loaded the first fragment instead of the selected fragment.
It seems that when the orientation change is produced, the activity is being recreated (I want it because I want the smart banner from admob to recreate with the new width), but the fragment probably is not being recreated or something, so probably it's pointing to a different fragment from the painted one.
How can I avoid this crash? maybe there is a way to tell the viewpager that it must load the page which is displaying? how can that be done?
I tried storing the current fragment number and selecting it when recreating but the crash is still happening:
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt("current_item", viewPager.getCurrentItem());
super.onSaveInstanceState(savedInstanceState);
}
.
.
.
//code in onCreate()
viewPager.setAdapter(collectionPagerAdapter);
if (savedInstanceState != null) {
int currentItem = savedInstanceState.getInt("current_item");
viewPager.setCurrentItem(currentItem);
}
This is my xml layout.
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/pager"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="3dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toTopOf="@+id/adView">
<android.support.v4.view.PagerTitleStrip
android:id="@+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingTop="4dp"
android:paddingBottom="4dp"
style="@style/CustomPagerTitleStrip"/>
</android.support.v4.view.ViewPager>
This is the line where is crashing in the StableArrayAdapter which fills the fragments with lines
Override public long getItemId(int position) {
return Math.abs(getItem(position).hashCode());
}
Upvotes: 0
Views: 446
Reputation: 1
You can go through below link, they have explained handling Fragments & viewPager orientation changes.
Upvotes: -1