viewPager adapter null pointer exception - android

I got an error while setting adapter, i only have one folder for layouts
and to tabs fragments on activity_main , i have searched in many websites but no results. Please help!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
mTitle = getTitle();
navMenuTitle = getResources().getStringArray(R.array.titles);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter); //Null Pointer Exception
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
getSupportActionBar().setTitle(navMenuTitle[position]);
}
});
this is the SectionAdapter
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch(position){
case 0:
return MainGenFragment.newInstance(position + 1);
case 1:
return new FragmentMyPwd();
}
return null;
}
#Override
public int getCount() {
// Show 3 total pages. Now Changed to 2.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
//case 2:
//return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}

You need to add setContentView(R.layout.yourlayout) in onCreate(). Without that, mViewPager will be null because it is not found with findViewById().

Related

Setting the names of each tab of viewpager

At the moment I have seven tabs that I are intially just blank, i.e. "". Those values would be changed to the values of a String[] array that I am passing through a method call shown below
So I have method like this in one of my classes:
CustomTabAdapter customTabAdapter = new CustomTabAdapter();
customTabAdapter.setTabNames(temps);
Basically this sets the tab names for the fragmentpager but it does not update the actual tabs. When I do print temps in this class via a for loop it prints all the names in temps - which means that temps exists but it never updates the tabs.
I believe it doesn't update because I am not overriding the original values in my CustomTabAdapter class but here is my CustomTabAdapter class:
public class CustomTabAdapter extends FragmentPagerAdapter {
String names[];
Context context;
public CustomTabAdapter(FragmentManager fragmentManager, Context context){
super(fragmentManager);
this.context = context;
names = new String[7];
Arrays.fill(names, "");
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new TabOne();
case 1:
return new TabTwo();
case 2:
return new TabThree();
case 3:
return new TabFour();
case 4:
return new TabFive();
case 5:
return new TabSix();
case 6:
return new TabSeven();
default:
return null;
}
}
public void setTabNames(String[] input){
names = Arrays.copyOf(input, input.length);
}
#Override
public int getCount() {
return names.length;
}
#Override
public CharSequence getPageTitle(int position) {
return names[position];
}
}
This is my TabsGUI where I display all the tabs:
public class TabsViewGUI extends AppCompatActivity {
TabLayout tabLayout;
ViewPager viewPager;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.users_page);
viewPager = (ViewPager) findViewById(R.id.viewPagerUsers);
CustomTabAdapter customTabAdapter = new CustomTabAdapter(getSupportFragmentManager(), TabsViewGUI.this);
viewPager.setAdapter(customTabAdapter);
viewPager.setOffscreenPageLimit(customTabAdapter.getCount());
populate();
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
//viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
//viewPager.setCurrentItem(tab.getPosition());
}
});
}
}
How do I update the tab names because they don't seem to be updating at the moment
Thanks
I've refreshed the tab names by calling notifyDataSetChanged after you've updated the names
public void setTabNames(String[] input){
names = Arrays.copyOf(input, input.length);
notifyDataSetChanged()
}
From the PagerAdapter javadoc:
This method should be called by the application if the data backing this adapter has changed and associated views should update.
I've noticed that in your adapter you're returning a new Fragment after each getItem() call. You should set the title of the fragment before returning it.
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
TabOne fragTab1 = new TabOne();
fragTab1.setTitle(names[position]);
return fragTab1;
(...)
default:
return null;
}
}

How can I set fragment Id in some of the override method of FragmentPagerAdapter?

I have a FragmentPagerAdapter, and in the fragment class I have a public method that I need to use from main activity.
In this point I don't know how to access the fragment that contains that method. Can I modify something on the class below to set id or something to fragments?
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Fragment_1();
case 1:
return new Fragment_2();
case 2:
return new Fragment_3();
}
return null;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.fg_1).toUpperCase(l);
case 1:
return getString(R.string.fg_2).toUpperCase(l);
case 2:
return getString(R.string.fg_3).toUpperCase(l);
}
}
return null;
}
}
How can I set a Fragment id, or Fragment tag or something to acces the fragment later?
Any other way to access fragment methods could be good.
EDITED WITH MORE INFORMATION:
I'm really lost with this. But, I have a ViewPager too, these fragments are associated to actionBar Tabs.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener(){
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
}
Is there any way to communicate with the fragments?
Like so :
switch (position) {
case 0:
Fragment f = new Fragment_1();
f.setId(...);
return f;
case 1:
...
}
This assumes you have a setId method in your fragment.
What I do however is define a static string TAG per fragment, I can then access it with Fragment_1.TAG.

Delay tab fragment creation

I am implementing tabs:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case 0: {
fragment = new Fragment1();
break;
}
case 1: {
fragment = new Fragment2();
break;
}
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return "Fragment1";
case 1:
return "Fragment2";
}
return null;
}
}
Activity:
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
Tab tab = actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i));
tab.setTabListener(this);
actionBar.addTab(tab, i == 0); // Select first tab
}
What I am finding is that each view is created up front, i.e. the view is created before its tab is selected. Is there a way to delay creation of tabs that have not been selected?
if you just want to delay the creation of tabs try this :
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case 0: {
// 3000 = SECONDS DELAY
new CountDownTimer(3000, 1000) {
public void onTick(long millisUntilFinished) {}
public void onFinish() {
// INFLATE VIEW HERE
fragment = new Fragment1();
}
}.start();
break;
}
case 1: {
// 3000 = SECONDS DELAY
new CountDownTimer(3000, 1000) {
public void onTick(long millisUntilFinished) {}
public void onFinish() {
// INFLATE VIEW HERE
fragment = new Fragment2();
}
}.start();
break;
}
}
return fragment;
}
I dont know if this is what youre looking but i hope it will help you :)

FragmentPagerAdapter getItem wrong position

I've got strange problem with FramentPageAdapter
MainActivity.java
#SuppressLint("ValidFragment")
public class MainActivity<DashboardActivity> extends FragmentActivity implements ActionBar.TabListener {
...
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(0)).setTabListener(this).setIcon(R.drawable.rating_good));
actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(1)).setTabListener(this).setIcon(R.drawable.action_search));
actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(2)).setTabListener(this).setIcon(R.drawable.action_search));
}
...
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
public Fragment getItem(int position) {
Fragment fragment = null;
switch(position) {
case 0:
fragment = new Fragment0();
break;
case 1:
fragment = new Fragment1();
break;
case 2:
fragment = new Fragment2();
break;
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
/*
* Title
*/
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section0).toUpperCase(l);
case 1:
return getString(R.string.title_section1).toUpperCase(l);
case 2:
return getString(R.string.title_section2).toUpperCase(l);
}
return null;
}
}
public Fragment getItem(int position) return wrong position when i try to switch between 3 tabs. When i create app with 2 tabs only, everything work just fine. Adding more then 2 of them, creating strange problem.
Switch from 0 to 1 position - works fine, switch from 1 to 0 - works fine, switch from 1 to 2 posiition - works fine, but, when i try to go back from 2 to 1 position, public Fragment getItem(int position) - int position return "0" instead of "1".
Does anyone help me with this ?
Ok, I've found the solution.
First of all, the getItem "int position", doesn't indicate current display fragment.
To display 3 or more tabs, without unload firts fragment You must added this line:
mViewPager.setOffscreenPageLimit(3);
End of story...
You just need:
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Log.d("test", "position = " + position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
The position in onPageSelected is what you want.
I had had the same problem, and I used fragment inside each tabs;
So instead of
mViewPager.setAdapter(new MainTabs(getFragmentManager()));
use this one:
mViewPager.setAdapter(new MainTabs(getChildFragmentManager()));
In case anyone else has this issue, I solved it by not using the position given. Instead, I get a List of Fragment with getSupportFragmentManager, loop through, and check if the current Fragment is instanceof my desired Fragment.

How to access ImageButton from fragment in fragment activity?

I am using ViewPager and loading multiple fragment in Fragment Activity using FragmentPage Adapter. I want to access a fragment which contains an ImageButton. Can any one help me to access Imagebutton from fragment in fragment activity?
Here is my code :
Fragment Activity
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_gallery);
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (CustomPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mPager.setOnPageChangeListener(this);
pagerLayout = (LinearLayout) findViewById(R.id.tour_pager_lay);
mPageControl = (PageControl)findViewById(R.id.horizontal_pager);
mPageControl.addPagerControl(3);
}
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 3;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new ImageFragment(R.drawable.landing_logo);
case 1:
return new ImageFragment(R.drawable.welcome_postit);
case 2:
return new LoginFragment();
case 4:
return new RegisterFragment();
default:
return null;
}
}
}
Suppose that your ImageButton is on your RegisterFragment, then you can do:
RegisterFragment tmp = ((RegisterFragment) ((MyAdapter) mPager.getAdapter()).instantiateItem(mPager, 4));
//your ImageButton should be public or you can create a getter or something, I assume that it's public
tmp.imageButton.setText("foo");

Categories

Resources