Thursday, 8 August 2013

ViewPager setAdapter null pointer exception after rotate

ViewPager setAdapter null pointer exception after rotate

I get null pointer exception in MainActivity only when trying to rotate
device.
Here is my onCreate method:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity = this;
mSectionsPagerAdapter = new
SectionsPagerAdapter(getSupportFragmentManager());
pager = (ViewPager) findViewById(R.id.pager2);
Log.v("rotate", ""+ mSectionsPagerAdapter);
Log.v("rotate", ""+ pager);
pager.setAdapter(mSectionsPagerAdapter);
}
This is my activity_main.xml :
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/pager2"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!--
This title strip will display the currently visible page title, as well as
the page
titles for adjacent pages.
-->
<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:background="#e5e5e5"
android:paddingBottom="4dp"
android:paddingTop="4dp"
android:textColor="#fff"
/>
My FragmentPagerAdapter:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch(position) {
case 0:
Fragment fragment = new SettingsFragment(cities);
Bundle args = new Bundle();
args.putInt("section_number", position);
fragment.setArguments(args);
return fragment;
case 1:
Fragment weatherNowFragment = new WeatherNowFragment();
Bundle args1 = new Bundle();
args1.putInt("section_number", position);
weatherNowFragment.setArguments(args1);
return weatherNowFragment;
case 2:
Fragment weatherHourlyFragment = new WeatherHourlyFragment();
Bundle args2 = new Bundle();
args2.putInt("section_number", position);
weatherHourlyFragment.setArguments(args2);
return weatherHourlyFragment;
case 3:
Fragment fragment3 = new DummySectionFragment();
Bundle args3 = new Bundle();
args3.putInt("section_number", position);
fragment3.setArguments(args3);
return fragment3;
default:
return null;
}
}
@Override
public int getCount() {
return 4;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return
getResources().getString(R.string.settings).toUpperCase(l);
case 1:
return
getResources().getString(R.string.weather_now).toUpperCase(l);
case 2:
return
getResources().getString(R.string.weather_hourly).toUpperCase(l);
case 3:
return
getResources().getString(R.string.weather_forecast).toUpperCase(l);
}
return null;
}
}
Basically everything is like in Google sample code.

No comments:

Post a Comment