FragmentAdapter doesn't hold the good reference of the fragment - android

I'm currently trying to work with fragment, but I'm stuck with an issue I can't solve.
I have one activity, which holds 4 different fragment. From this activity, I launch an ASyncTask which goes to the web and get different data I need, and then will send it to the fragments.
But, when my app gets killed and opened again, or when I change the orientation, my fragments are apparently recreated and my custom FragmentAdapter doesn't hold the good reference to the fragment.
Here is the code of my main activity.
public class MainActivity extends FragmentActivity {
MyPagerAdapter fgsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//...
FragmentManager fm = super.getSupportFragmentManager();
fgsAdapter = new MyPagerAdapter(fm,this);
ViewPager myPager = (ViewPager) findViewById(R.id.home_pannels_pager);
myPager.setAdapter(fgsAdapter);
myPager.setCurrentItem(0);
}
#Override
protected void onResume() {
super.onResume();
ATaskGetUser task = new ATaskGetUser(callback, (ProgressBar) findViewById(R.id.PB_AsyncTask));
task.execute();
}
//What's called by the ASyncTask onPostExecute()
private void notifyDataChanged() {
fgsAdapter.notifyFragments(user.getItems());
}
private class MyPagerAdapter extends FragmentPagerAdapter {
private List<CardFragment> fragments = new ArrayList<CardFragment>();
private Context c;
public MyPagerAdapter(FragmentManager fm, Context c) {
super(fm);
CardFragment h = new HabitFragment();
CardFragment d = new DailyFragment();
CardFragment t = new ToDoFragment();
CardFragment r = new RewardFragment();
fragments.add(h);
fragments.add(d);
fragments.add(t);
fragments.add(r);
}
public int getCount() {
return fragments.size();
}
#Override
public CardFragment getItem(int position) {
Log.v("MainActivity_fgsmanager", "getItem()");
CardFragment f = (CardFragment) this.fragments.get(position);
return f;
}
public void notifyFragments(List<HabitItem> items) {
for(OnTasksChanged f : fragments) {
f.onChange(items);
}
}
}
}
So, what I want to be able to do, is to be able to call the onChange (an interface implemented by my four fragments), in my notifyDataChanged function. Is this possible, are am I thinking the wrong way?

I got the same problems once with Fragments, I was losing the current fragment after every screen rotation.
I simply solved it by adding one line in the Fragment class (not in the parent FragmentActivity class):
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.rate_fragment, container,false);
setRetainInstance(true);//Added not to lose the fragment instance during screen rotations
(...)
For your case where your app gets killed and opened again, I am not sure it will work though.

Related

Refresh a Fragment from mainactivity

I have an Activity with three tabs and three Fragments. First Fragment shows the list of song titles and the second tab displays the selected song. The details of the songs is coming from a database.
I am implementing SearchView feature so that whatever search text user enters, only those songs should be displayed in the index.
This is exactly like the way phone book work in our devices.
I'm not able to understand how to refresh the first Fragment when the search query changes.
I'm basically looking for the method that I can call to refresh the first Fragment.
Got my answer here Android refresh a fragment list from its parent activity as suggested by #Prem. Works perfectly fine for me.
Its is achievable by making an interface
MainActivity.java
public class MainActivity extends Activity {
public FragmentRefreshListener getFragmentRefreshListener() {
return fragmentRefreshListener;
}
public void setFragmentRefreshListener(FragmentRefreshListener fragmentRefreshListener) {
this.fragmentRefreshListener = fragmentRefreshListener;
}
private FragmentRefreshListener fragmentRefreshListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button)findViewById(R.id.btnRefreshFragment);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(getFragmentRefreshListener()!=null){
getFragmentRefreshListener().onRefresh();
}
}
});
}
public interface FragmentRefreshListener{
void onRefresh();
}}
MyFragment.java
public class MyFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = null; // some view
/// Your Code
((MainActivity)getActivity()).setFragmentRefreshListener(new MainActivity.FragmentRefreshListener() {
#Override
public void onRefresh() {
// Refresh Your Fragment
}
});
return v;
}}
Below is the one way, you can easily do it. You just have to save the fragment instance. That's all.
private class ViewPagerAdapter extends FragmentStatePagerAdapter {
private SparseArray<Fragment> array = new SparseArray<>();
ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
array.setValueAt(position, myFragment);
return myFragment;
}
#Override
public int getCount() {
return 3;
}
public SparseArray<Fragment> getFragmentArray() {
return array;
}
}
Then from your activity, you can get all viewpager fragment easily from adapter instance.
MyFragment fragment = (MyFragment) adapter.getFragmentArray().get(0); // get first fragment and casting it to your origin fragment
Then create a method on that fragment. Call like below:
fragment.myFragmentMethod(String myData){}
Have a nice day!

update object in swipe view

I'm trying to update an object from a fragment contained within a swipe view. The code I have is taken directly from the Android documentation. What I want to do is pass an object from the main CollectionDemoActivity down into the DemoObjectFragment fragment, update it using a button in that fragment and then pass it back up to the main activity. What's the best way to accomplish this?
I've tried passing the object in a bundle as a serialisable through the DemoCollectionPagerAdapter and then again down to the fragment but this seems really cumbersome. I've also tried declaring the object in the main activity and just referencing it in the fragment class but I get complaints that it can't have a non-static reference in a static context.
public class CollectionDemoActivity extends FragmentActivity {
// When requested, this adapter returns a DemoObjectFragment,
// representing an object in the collection.
DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;
ViewPager mViewPager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collection_demo);
// ViewPager and its adapters use support library
// fragments, so use getSupportFragmentManager.
mDemoCollectionPagerAdapter =
new DemoCollectionPagerAdapter(
getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
}
}
// Since this is an object collection, use a FragmentStatePagerAdapter,
// and NOT a FragmentPagerAdapter.
public class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new DemoObjectFragment();
Bundle args = new Bundle();
// Our object is just an integer :-P
args.putInt(DemoObjectFragment.ARG_OBJECT, i + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 100;
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
// Instances of this class are fragments representing a single
// object in our collection.
public static class DemoObjectFragment extends Fragment {
public static final String ARG_OBJECT = "object";
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// The last two arguments ensure LayoutParams are inflated
// properly.
View rootView = inflater.inflate(
R.layout.fragment_collection_object, container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(android.R.id.text1)).setText(
Integer.toString(args.getInt(ARG_OBJECT)));
return rootView;
}
}
So after a lot of searching and reading I found a nice solution that works for me. For those interested I created an interface in the fragment class that is implemented in the Main activity. The methods were kicked off through a button press in the fragment class. This way I was able to pass variables up to the main class without ever needing to pass the entire object down to the fragment.
So my classes were mostly the same with these bits added:
And the fragment class which contains the interface. The onAttach() method needs to be called which gets a reference to the activity that the fragment will be attached to. This activity reference is binded to an instance of the interface in the fragment.
public class DemoObjectFragment extends Fragment {
....
//Creating the interface
public interface ButtonListener {
//This method will be called in the main activity. Whatever is passed in as the parameter can be used by the main activity
public void ButtonPressed(int myInt);
}
//Getting an instance of the interface
ButtonListener updateListener;
//Getting a reference to the main activity when the fragment is attached to it.
//The activity reference is bound to the instance of the interface.
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Ensures the activity implements the callback interface
try {
updateListener = (DayUpdateButtonListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString());
}
}
....
//On the button click call the method through the activity reference from the onAttach() method
//Creating an int object to pass into the method.
int myNewInt = 5;
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
updateListener.ButtonPressed(myNewInt);
}
});
}
Finally in the main activity simply implement the interface and add the method from it.
public class CollectionDemoActivity extends FragmentActivity implements DemoObjectFragment.ButtonListener {
....
#Override
public void ButtonPressed(int myInt) {
//Update the object with myInt
}
}

Android Fragments stored as array in FragmentPagerAdapter not refreshed after leaving and coming back to app

I'm having a strange issue with fragment views not refreshing properly, but it only happens after the app is closed and re-opened after some amount of time.
I have a TabSwitcherActivity which contains a ViewPager. The ViewPager switches between 3 fragments, and each fragment represents a different view of the same information. There are certain events that can happen which will cause the information to become stale, so the fragments need to be notified to refresh the view. To accomplish this, my TabSwitcherActivity has a method called notifyDataSetChanged() which will iterate the 3 fragments and tell them to refresh. Here is (I think) the most relevant code:
public class TabSwitcherActivity extends FragmentActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Used to keep track of the child fragments of this activity so we can update their list adapters.
mFragments = new ArrayList<Fragment>();
// Set up the view pager and tab adapter.
setContentView(R.layout.pager_layout);
mViewPager = (ViewPager) super.findViewById(R.id.pager);
mFragments.add(Fragment.instantiate(this, FragmentOne.class.getName()));
mFragments.add(Fragment.instantiate(this, FragmentTwo.class.getName()));
mFragments.add(Fragment.instantiate(this, FragmentThree.class.getName()));
mViewPager.setAdapter(new ListPagerAdapter(super.getSupportFragmentManager(), mFragments));
}
public void notifyDataSetChanged() {
for (Fragment fragment : mFragments) {
if (fragment instanceof IDataSetChangedListener) {
((IDataSetChangedListener) fragment).notifyDataSetChanged();
}
}
}
}
Now, this works as intended the first time the app is launched. The problem is that after the app is closed and re-opened some time later, calling TabSwitcherActivity.notifyDataSetChanged() while the app is running does not update the fragment views (this works the first time the app is started after a reboot). This leads me to believe that there is a life cycle situation with the fragments that I'm not handling correctly. Any idea what this might be? It occurs to me that If the fragments are destroyed and recreated, they are probably not correctly stored in my mFragments array.
I'm answering my own question in case others have a similar problem to what I had. I was able to resolve the problem based on the comments from invertigo. I'll post some generified pieces of the important parts of the code.
As I suspected, the fragments stored in the array were not correctly updated if they were destroyed and re-created by the application. (This would sometimes happen when the application was closed and re-opened.) It was a little bit tricky to remove the array since I was using it to store the fragments for my tabs in my FragmentPagerAdapter implementation.
Here is my old ListPagerAdapter class:
public class ListPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> mFragments;
public ListPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
mFragments = fragments;
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public String getPageTitle(int position) {
return ((ITitledFragment) mFragments.get(position)).getTitle();
}
}
Here is my new implementation, which removes the problem caused by the array holding bad fragment references:
public class ListPagerAdapter extends FragmentPagerAdapter {
private static final int FRAGMENT_ONE_POSITION = 0;
private static final int FRAGMENT_TWO_POSITION = 1;
private static final int FRAGMENT_THREE_POSITION = 2;
private static final int COUNT = 3;
public ListPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case FRAGMENT_ONE_POSITION:
return new FragmentOne();
case FRAGMENT_TWO_POSITION:
return new FragmentTwo();
case FRAGMENT_THREE_POSITION:
return new FragmentThree();
}
return null;
}
#Override
public int getCount() {
return COUNT;
}
#Override
public String getPageTitle(int position) {
switch (position) {
case 0:
return FragmentOne.getTitle();
case 1:
return FragmentTwo.getTitle();
case 2:
return FragmentThree.getTitle();
}
return null;
}
}
Then, the only remaining problem is how to have the my TabSwitcherActivity class update all of the fragments when they are stale. As invertigo pointed out, this can be done with tags. However, I decided to use an approach where each fragment registers itself with the activity when it is created, and unregisters itself before it is destroyed. The activity can iterate registered fragments to update them.
The Relevant code from TabSwitcherActivity:
class TabSwitcherActivity extends FragmentActivity {
private List<Fragment> mFragments;
private void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Used to keep track of the child fragments of this activity so we can update their list adapters.
mFragments = new ArrayList<Fragment>();
// Set up the view pager and tab adapter.
setContentView(R.layout.pager_layout);
mViewPager = (ViewPager) super.findViewById(R.id.pager);
mViewPager.setAdapter(new ListPagerAdapter(super.getSupportFragmentManager()));
}
public void startTrackingFragment(Fragment f) {
mFragments.add(f);
}
public void stopTrackingFragment(Fragment f) {
mFragments.remove(f);
}
public void notifyDataSetChanged() {
for (Fragment fragment : mFragments) {
if (fragment instanceof IDataSetChangedListener) {
((IDataSetChangedListener) fragment).notifyDataSetChanged();
}
}
}
}
With that, all that remains is to have the fragments register themselves for updates:
public class FragmentOne extends Fragment implements IDataSetChangedListener {
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
((TabSwitcherActivity) getActivity()).startTrackingFragment(this);
}
public void onDestroy() {
((TabSwitcherActivity) getActivity()).stopTrackingFragment(this);
super.onDestroy();
}
}
You could always just refresh the data in onResume() of your fragments, or call notifyDataSetChanged() in onResume() of your activity.
re: "It occurs to me that If the fragments are destroyed and recreated, they are probably not correctly stored in my mFragments array."
Instead of storing the fragments in an array, use the fragment manager to fetch the fragments by tag or id.
http://developer.android.com/guide/components/fragments.html#Managing
http://developer.android.com/reference/android/app/FragmentManager.html#findFragmentByTag(java.lang.String)

ViewPager and Activity recreation / persisting data in fragments after activity onDestroy-onCreate

I wrote an activity with ViewPager, which gets populated after an AsyncTask is executed. Each TestDataObject is tied to the relevant TestFragment. When the screen is rotated the application crushes due to a NullPointerException inside onCreateView method. I believe this is because of ViewPager/Adapter onSaveInstanceState methods, onCreateView tries to restore data prior to the AsyncTask data load when data isn't available yet.
I could just if onCreateView code but it doesn't feel to me like a right solution, because amount of fragments inside ViewPager might vary so it might end up doing unnecessary job: restore altered viewpager content and then replace with initial. In this case onSaveInstanceState seems to be excessively harmful. Presumably, I could extend ViewPager or Adapter to cancel save procedure - I find it weird as well.
Do you have any better suggestions to offer?
public class MainActivity extends LoggerActivity {
private ArrayList<TestDataObject> mDataObjects = new ArrayList<MainActivity.TestDataObject>();
private ViewPager mViewPager;
private TestFragmentAdapter mViewPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPagerAdapter = new TestFragmentAdapter(
getSupportFragmentManager(), mDataObjects);
mViewPager.setAdapter(mViewPagerAdapter);
new TestAsyncTask().execute();
}
private class TestAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mDataObjects.add(new TestDataObject());
mDataObjects.add(new TestDataObject());
mDataObjects.add(new TestDataObject());
mViewPagerAdapter.notifyDataSetChanged();
}
}
public static class TestFragment extends Fragment {
private TestDataObject mDataObject;
public static TestFragment getInstance(TestDataObject obj) {
TestFragment f = new TestFragment();
f.mDataObject = obj;
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// layout.find...
mDataObject.toString();
return inflater.inflate(R.layout.fragment_test, null, false);
}
}
public static class TestFragmentAdapter extends FragmentStatePagerAdapter {
private List<TestDataObject> mDataObjects;
public TestFragmentAdapter(FragmentManager fm, List<TestDataObject> objs) {
super(fm);
mDataObjects = objs;
}
#Override
public Fragment getItem(int position) {
return TestFragment.getInstance(mDataObjects.get(position));
}
#Override
public int getCount() {
return mDataObjects == null ? 0 : mDataObjects.size();
}
}
public static class TestDataObject {
}
}
I believe this is because of ViewPager/Adapter onSaveInstanceState
methods. onCreateView tries to restore data prior to the asynctask
dataload when data isn't available yet.
That is not what is happening(I'm assuming you get the exception at mDataObject.toString();), even if the AsyncTask would finish its job instantaneously the exception will still be thrown. After the first run of the app the ViewPager will have three fragments in it. When you'll turn the phone the Activity will be destroyed an recreated again. The ViewPager will try to recreate the fragments in it, but this time it will do it by using the default empty constructor(that is why you shouldn't use a non empty constructor to pass data). As you can see, the first time the Fragment is created by the adapter it will be created by the getInstance method(that is also the only point where you initialize mDataObject) to which you pass a TestDataObject object. When the ViewPager reinitializes its fragments that field will not be initialized as well.
If TestDataObject can be put in a Bundle then you could simply adapt your getInstance method to pass some arguments to your fragments(so the data field will be initialized when the ViewPager will recreate them). I'm sure you've seen:
public static TestFragment getInstance(TestDataObject obj) {
TestFragment f = new TestFragment();
// f.mDataObject = obj; <- don't do this
// if possible
Bundle args = new Bundle();
args.put("data", obj); // only if obj can be put in a Bundle
f.setArguments(args);
return f;
}
private TestDataObject mDataObject;
#Override
public void onCreate(Bundle savedInstance) {
mDataObject = getArguments().get("data"); // again, depends on your TestDataObject
}
Another approach would be to pass the smallest amount of data to the Fragment(like above) so it has enough information to recreate it's data whenever it's recreated.

Android app crashing after a while using Fragments and ViewPager

I've got a problem with my android app crashing when trying to restore my fragments. I have not added any custom variables to the bundle that I'm trying to restore, It's all default. I'm using Fragments and ViewPager. See my code snippets below:
public static class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return NUM_ITEMS;
}
public int getCurrentItemPosition(Fragment fragment){
return getItemPosition(fragment);
}
#Override
public Fragment getItem(int position) {
return ContentFragment.newInstance(position);
}
}
public class MyActivity extends FragmentActivity {
static final int NUM_ITEMS = 100000;
public int currentSelectedPage;
private int changeToFragmentIndex;
public DateTime midDate;
MyAdapter mAdapter;
ViewPager mPager;
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.diary);
MyApplication application = (MyApplication)getApplication();
application.dataController.myActivity = this;
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
int newDay = application.daysBetween(DateTime.now(), DateTime.parse(application.day.dateToShortString()));
this.currentSelectedPage = NUM_ITEMS/2+newDay;
mPager.setCurrentItem(NUM_ITEMS/2+newDay);
mPager.setOnPageChangeListener(new SimpleOnPageChangeListener(){
public void onPageSelected(int position){
currentSelectedPage = position;
ContentFragment fragment = (ContentFragment) mAdapter.instantiateItem(mPager, currentSelectedPage);
fragment.loadData();
}
});
}
}
public class ContentFragment extends Fragment {
private View v;
static final int NUM_ITEMS = 100000;
static ContentFragment newInstance(int num) {
ContentFragment f = new ContentFragment();
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null)
return null;
v = inflater.inflate(R.layout.diarycontent, container, false);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
setUserVisibleHint(true);
}
}
I receive this stackstrace:
Caused by: java.lang.NullPointerException
at android.support.v4.app.FragmentManagerImpl.getFragment(FragmentManager.java:519)
at android.support.v4.app.FragmentStatePagerAdapter.restoreState(FragmentStatePagerAdapter.java:1 55)
at android.support.v4.view.ViewPager.onRestoreInstanceState(ViewPager.java:522)
As I have understood this may be a known problem with the support package and that one possible solution would be to use setUserVisibleHint(true) in onSaveInstanceState. But that didn't help.
Does anyone know another solution to the problem or what I've done wrong?
I have faced same type of issue once I started using ViewPager with FragmentStatePagerAdapter inside Tab.
Then I played with all forums related to this issue and break my head for two days to find out why this issue is occurred and how to resolve it but does not found any perfect solution that fulfills as per my requirement.
I got the solution as in order to avoid the NPE crash use FragmentPagerAdapter instead of FragmentStatePagerAdapter. When I replace FragmentPagerAdapter instead of FragmentStatePagerAdapter then not faced NPE crash issue but the same page is not refreshed itself for further navigation(which is my requirement).
Finally override the saveState method on FragmentStatePagerAdapter and everything working fine as expected.
#Override
public Parcelable saveState() {
// Do Nothing
return null;
}
How I reproduce this issue easily :
I am using the higher version(4.1) device and followed the below steps:
1. Go to Settings -> Developer Options.
2. Click the option "Do not keep activities".
Now I played with my app.
Before override the saveState() method each time the app is crashing due to the NPE at android.support.v4.app.FragmentManagerImpl.getFragment(Unknown Source). But after override saveState() no crash is registered.
I hope by doing so you will not having any issue.
I initially used solution suggested by #Lalit Kumar Sahoo. However, I noticed a serious issue: every time I rotated the device, the Fragment Manager added new fragments without removing the old ones. So I searched further and I found a bug report with a workaround suggestion (post #1). I used this fix and tested with my app, the issue appears to be resolved without any side-effects:
Workaround: Create custom FragmentStatePagerAdapter in project's src/android/support/v4/app folder and use it.
package android.support.v4.app;
import android.os.Bundle;
import android.view.ViewGroup;
public abstract class FixedFragmentStatePagerAdapter extends FragmentStatePagerAdapter {
public FixedFragmentStatePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment f = (Fragment)super.instantiateItem(container, position);
Bundle savedFragmentState = f.mSavedFragmentState;
if (savedFragmentState != null) {
savedFragmentState.setClassLoader(f.getClass().getClassLoader());
}
return f;
}
}
Why exactly are you doing:
mPager.setOnPageChangeListener(new SimpleOnPageChangeListener(){
public void onPageSelected(int position){
currentSelectedPage = position;
ContentFragment fragment = (ContentFragment) mAdapter.instantiateItem(mPager, currentSelectedPage);
fragment.loadData();
}
});
This:
#Override
public Fragment getItem(int position) {
return ContentFragment.newInstance(position);
}
Instantiates the fragment.
You can load data like this in the fragment :
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
loadData();
}

Categories

Resources