How to start fragments after pressing on the action bar? - java

I made 2 different fragments and I want them to show in the 2 tabs. One fragment after pressing the first tab and the other fragment after pressing the second tab. After switching between the two tabs, only one fragment should be shown.
my first fragment names "fragment" and my second fragment is named "fragment2"
//Hallo ich hätte gerne tabs
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//tab listener
ActionBar.TabListener tabListener1 = new ActionBar.TabListener(){
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
};
// für den zweiten tab
ActionBar.TabListener tabListener2 = new ActionBar.TabListener(){
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
};
//Tabs erstellen
actionBar.addTab(actionBar.newTab().setText("Tab Nummer Eins").setTabListener(tabListener1));
actionBar.addTab(actionBar.newTab().setText("Tab Nummer Zwei").setTabListener(tabListener2));

When you are communicating with more then one fragments better use FragmentStatePagerAdapter, which will populate required fragment on corresponding tab selected.
First Create Toolbar,Tablayout,ViewPager in your xml file.
Then Create Fragment and Fragment2.
Include this code in your HomeActivity.class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.list_home));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.save));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PageAdapter adapter = new PageAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
Log.i("tag1","on tab");
viewPager.setCurrentItem(tab.getPosition());// passing selected tab position to adapter and getting reuqired fragment
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
Create a PageAdapter like this...
public class PageAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PageAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Fragment tab1 = new Fragment(); //When click First tab
return tab1;
case 1:
Fragment2 tab2 = new Fragment2(); //When click on second tab
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
Log.i("tag1","on getcount");
return mNumOfTabs;
}
}
Hope this will help you. Let me know if you need any further help.

Related

How to start new Activity or refresh current Activity using viewpager

I have viewpager which is in fragment. I am looking to start a new activity or refresh the current activity using tabs on it
For now , I'm using this to open Fragment called "Sunday" and "Monday" But I would Like to add another tab and when user select this tab either refresh the current activity as same state when app is first opened or open new activity
Here is my code
public class MainActivity extends AppCompatActivity {
//RSS link
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new sectionB(), "SEC B");
viewPager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
//here yourDesiredPositionNumber is a int...like 0,1,2,3..according you
if (tab.getPosition() == 0) {
Intent i1 = new Intent(MainActivity.this, SagarActivity.class);
startActivity(i1);
//here you can do your refresh of start new activity
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
For Refresh
If you want to refresh whole activity you can call recreate() method of activity
in your case you are in a fragment so you need to get activity first so you can do like getActivity().recreate()
For start new activity
for open a new activity you can use startActivity()
i your case you can do Like this
Intent intent = new Intent(getActivity(),activity_you_want_to_start.class);
startActivity(intent);
Remember one more thing, always make user getActivity() not returning
null
Now in your case
you need to setup listener on your TabLayout like this then call above method
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabs_dayscount);
tabLayout.setupWithViewPager(viewPager);
//setting listener on tabLAyout
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
//here yourDesiredPositionNumber is a int...like 0,1,2,3..according you
if (tab.getPosition() == yourDesiredPositionNumber) {
//here you can do your refresh of start new activity
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
One Another Way is
You can also set Listener on ViewPager like this
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabs_dayscount);
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
//here yourDesiredPositionNumber is a int...like 0,1,2,3..according you
if(position==yourDesiredPositionNumber){
//here you can do your refresh of start new activity
}
super.onPageSelected(position);
}
});

How to fix TabIndicator not moving with selected tab

I am using a tablayout to build my application but the tab indicator is not working when I slide within the tabs. Can anyone help me?I have tried adding the addOnTabSelectedListener but that did not work either.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener{
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private PagerAdapter pagerAdapter;
private DrawerLayout drawerLayout;
private String[] pageTitle = {"myPlanner", "News", "Parking"};
private String studyRooms = "http://library2.csumb.edu/mrbs/mobilenow.php";
public static String MYPREFERENCE = "myPref";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
setSupportActionBar(toolbar);
//create default navigation drawer toggle
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
for (int i = 0; i < 3; i++) {
tabLayout.addTab(tabLayout.newTab().setText(pageTitle[i]));
}
//set gravity for tab bar
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//handling navigation view item event
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
assert navigationView != null;
navigationView.setNavigationItemSelectedListener(this);
viewPager = (ViewPager)findViewById(R.id.view_pager);
pagerAdapter = new PagerAdapter(getSupportFragmentManager(), MainActivity.this);
viewPager.setAdapter(pagerAdapter);
//setting Tab layout (number of Tabs = number of ViewPager pages)
//viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Fragment frag = pagerAdapter.fragments[position];
if(frag != null && frag instanceof MapsFragment){
Toast.makeText(MainActivity.this, "On page Selected", Toast.LENGTH_LONG).show();
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
// viewPager.setOffscreenPageLimit(3);
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));
}
class PagerAdapter extends FragmentPagerAdapter{
String tabTitles[] = new String[]{"myPlanner", "News", "Parking"};
public Fragment[] fragments = new Fragment[tabTitles.length];
Context context;
public PagerAdapter(FragmentManager fm, Context context){
super(fm);
this.context = context;
}
#Override
public int getCount(){
return tabTitles.length;
}
#Override
public Fragment getItem(int position){
switch (position){
case 0:
return new myPlanner();
case 1:
return new News();
case 2:
return new MapsFragment();
}
return null;
}
#Override
public CharSequence getPageTitle(int position){
//Generate title based on item position
return tabTitles[position];
}
#Override
public Object instantiateItem(ViewGroup container, int position){
Fragment createdFragment = (Fragment)super.instantiateItem(container,position);
fragments[position] = createdFragment;
return createdFragment;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[],int[] grantResults){
if(requestCode == MapsFragment.MY_PERMISSIONS_REQUEST_LOCATION){
MapsFragment mapFragment = (MapsFragment) pagerAdapter.fragments[2];
if(mapFragment != null){
mapFragment.onRequestPermissionsResult(requestCode,permissions,grantResults);
}
}
else{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
remove this:
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));
And add:
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
Also u should call tabLayout.setupWithViewPager(viewPager); after u set up the viewpager
viewPager = (ViewPager)findViewById(R.id.view_pager);
pagerAdapter = new PagerAdapter(getSupportFragmentManager(), MainActivity.this);
viewPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(viewPager);

How to load the fragment activity oncreate() method of the actionbar selected tab only if the tab is selected?

I am using viewpager and actionbar tabs (4 tabs). When the Main activity starts, it loads the 4 fragments data.
how to make it load only the selected tab data?
Also when I select tab 1, tab1 and tab0 loads.
If I swipe between tab0 and tab1 , onstart() for both tabs not called.
If I select tab2 and then select tab0, onstart() for tab0 loads.
If I swipe between tab2 and tab3 , onstart() for both tabs not called.
MainActivity.java
MainPagerAdapter tabsPagerAdapter;
ViewPager viewPager;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
tabsPagerAdapter = new MainPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(tabsPagerAdapter);
actionBar = getSupportActionBar();
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.addTab(actionBar.newTab().setIcon(getResources().getDrawable(R.drawable.doros)).setTabListener(this));
actionBar.addTab(actionBar.newTab().setIcon(getResources().getDrawable(R.drawable.esteshara)).setTabListener(this));
actionBar.addTab(actionBar.newTab().setIcon(getResources().getDrawable(R.drawable.aswak)).setTabListener(this));
actionBar.addTab(actionBar.newTab().setIcon(getResources().getDrawable(R.drawable.akhbar)).setTabListener(this));
viewPager.setOffscreenPageLimit(0);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.abs_layout);
viewPager.setOnPageChangeListener(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) {
}
});
viewPager.setCurrentItem(3);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
MainPageAdapter.java
public class MainPagerAdapter extends FragmentPagerAdapter implements PagerSlidingTabStrip.IconTabProvider{
public MainPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 4;
}
private int[] tabIcons = {
R.drawable.ar,
R.drawable.ar,
R.drawable.ar,
R.drawable.ar
};
#Override
public android.support.v4.app.Fragment getItem(int position) {
switch (position)
{
case 3: return new NewsFragment();
case 1: return new ConsultationFragment();
case 2: return new IndecesFragment();
case 0: return new LessonsFragment();
default: return null;
}
}
#Override
public int getPageIconResId(int i) {
return tabIcons[i];
}
}
I found this link, but its not helpful link
I have solved the problem.
I have created a static variable to store selected tab index.
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
sharedVariables.setSelectedTab(tab.getPosition());
Since Viewpager loads the selected page and the left page and the right page if they exist every time the page changed, so I override this function to check if this fragment is the one visible to user and then call onresume method.
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
onResume();
} else {
// Do your Work
}
}
With ViewPager I always extend Fragment setMenuVisibility(). It is called with true when the Fragment is visible, and with false when it's not. When it's visible, you can perform all the actions you need.

when i select the contacts tab the tab bar is vanished

i have four tabs in the tab bar when i select the contact tab from the tab bar the tab bar is disappeared.i want to show the tab bar when i select the contact tab.
Here is code
TabActivity.java
public class Tab_Activity extends TabActivity
{
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Resources obj_res = getResources();
TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);
TabSpec m_tab1 = tabHost.newTabSpec("First Tab");
TabSpec m_tab2 = tabHost.newTabSpec("Second Tab");
Intent intent1 = new Intent().setClass(this, Phone.class);
Intent intent3 = new Intent().setClass(this, Settings.class);
Intent intent4 = new Intent().setClass(this, Contact.class);
m_tab4.setIndicator("Tab4");
m_tab4=tabHost.newTabSpec("tab4").setIndicator("", obj_res.getDrawable(R.drawable.pic1)).setContent(intent3);
m_tab5.setIndicator("Tab4");
m_tab5=tabHost.newTabSpec("tab4").setIndicator("", obj_res.getDrawable(R.drawable.pic3)).setContent(intent4);
tabHost.addTab(m_tab2);
tabHost.addTab(m_tab4);
tabHost.addTab(m_tab5);
}}
Contact.java
public class Contact extends Activity
{
protected void onCreate(Bundle savedInstanceState)
{
//this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
//setContentView(R.layout.contact);
Intent Contacts = new Intent(Intent.ACTION_GET_CONTENT);
Contacts.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
Contacts.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(Contacts, 1);
}}
This is your activity in which u can put how many tab you want to display.
public class GuestListAdminActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Bride", "Groom", "Create Gueset List" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_guest_list_admin);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
getActionBar().setHomeButtonEnabled(true);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
This is pager adapter which will show your all fragments.
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new BrideGuestList();
case 1:
return new GroomGuestList();
case 2:
return new NewGuestListActivity();
default:
break;
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
}
And make your fragment activity like following
public class BrideGuestList extends android.support.v4.app.Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.bride_guest_list, container, false);
return rootView;
}

SlidingMenu with ViewPager and ActionBarSherlock Tabs

In my calendar application, I am using ActionBarSherlock to display two tabs - 1) Calendar 2) Converter. On the click event of an ActionBar menu item, I'm using SlidingMenu drawer to display event summary for that month.
I want to use viewpager specifically for the Calendar tab and I have implemented it this way:
Main.java:
public class BaseActivity extends SlidingSherlockFragmentActivity
{
private ViewPager pager;
CalendarFragmentPagerAdapter mPagerAdapter;
private static final int MONTHS_LIMIT = 5;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(R.string.app_name);
setContentView(R.layout.main);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main, new CalendarFragment())
.commit();
setBehindContentView(R.layout.content_frame);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, new EventsSummary())
.commit();
setSlidingActionBarEnabled(false);
final ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setHomeButtonEnabled(true);
ActionBar.Tab calendar = bar.newTab();
ActionBar.Tab converter = bar.newTab();
calendar.setText(this.getResources().getString(R.string.calendar));
converter.setText(this.getResources().getString(R.string.converter));
calendar.setTabListener(new MyTabListener());
converter.setTabListener(new MyTabListener());
bar.addTab(calendar);
bar.addTab(converter);
// customize the SlidingMenu
SlidingMenu sm = getSlidingMenu();
sm.setShadowWidthRes(R.dimen.shadow_width);
sm.setShadowDrawable(R.drawable.shadow);
sm.setBehindOffsetRes(R.dimen.actionbar_home_width);
sm.setSlidingEnabled(false);
mPagerAdapter = new CalendarFragmentPagerAdapter(getSupportFragmentManager());
pager = (ViewPager) this.findViewById(R.id.viewpager);
pager.setAdapter(mPagerAdapter);
pager.setCurrentItem(MONTHS_LIMIT / 2);
}
private class MyTabListener implements ActionBar.TabListener
{
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if(tab.getPosition()==0)
{
CalendarFragment frag = new CalendarFragment();
ft.replace(R.id.main, frag);
}
else
{
ConverterFragment frag = new ConverterFragment();
ft.replace(R.id.main, frag);
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
public boolean onOptionsItemSelected(MenuItem item) {
Intent newActivity;
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_slidingmenu:
toggle();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public class CalendarFragmentPagerAdapter extends FragmentPagerAdapter {
public CalendarFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
CalendarFragment fragment = new CalendarFragment();
Bundle args = new Bundle();
args.putInt("offset", position - MONTHS_LIMIT / 2);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return MONTHS_LIMIT;
}
}
}
CalendarFragment.java:
public class CalendarFragment extends Fragment
{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
int offset = args.getInt("offset"); //throws NullPointerException
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.simple_calendar_view, container, false);
.....
return v;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("dummy", true);
}
}
The problem is at this line in the CalendarFragment:
int offset = args.getInt("offset");
It throws the error NullPointerException and debugging shows this is because Bundle args = getArguments() is null.
I tried to put the breakpoint at this line in the PagerAdapter:
Bundle args = new Bundle();
but it never reaches here and the application crashes throwing the NullPointerException.
Where am I going wrong?
Here
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main, new CalendarFragment())
.commit();
and here
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (tab.getPosition() == 0) {
CalendarFragment frag = new CalendarFragment();
ft.replace(R.id.main, frag);
} else {
ConverterFragment frag = new ConverterFragment();
ft.replace(R.id.main, frag);
}
}
you're just creating an empty CalendarFragment instance without any arguments.
So your activity launches, creating an empty Fragment without arguments, and then crashes when trying to get those

Categories