I have tried unsuccessfully to pass the context of SimpleFragmentPageAdapter via its constructor to the MainActivity, calling getResources().getString() on this context variable, in order to retrieve the titles for each tab in the page adapter.
Any help is much appreciated!
SimpleFragmentPageAdapter.java
public class SimpleFragmentPageAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 5;
private Context context;
String tabOne = context.getResources().getString(R.string.kiez);
String tabTwo = context.getResources().getString(R.string.history);
String tabThree = context.getResources().getString(R.string.culture);
String tabFour = context.getResources().getString(R.string.food);
String tabFive = context.getResources().getString(R.string.green);
private String[] tabNames = new String [] {tabOne, tabTwo, tabThree, tabFour, tabFive};
public SimpleFragmentPageAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set view to activity:main
setContentView(R.layout.activity_main);
// Find ViewPager for easy swiping
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
// Create adapater object to know which fragment should be shown based on user interaction
SimpleFragmentPageAdapter pagerAdapter = new SimpleFragmentPageAdapter(getSupportFragmentManager(), this);
// Set adapter to ViewPager
viewPager.setAdapter(pagerAdapter);
// Find TabLayout for tab identification
TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
// Set ViewPager to TabLayout
tabLayout.setupWithViewPager(viewPager);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<android.support.design.widget.TabLayout
android:id="@+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"/>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Relevant error log for reference:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference