Restoring object references after Activity is killed and restored - android

I have a FragmentPagerAdapter that pages through views generated by a custom SurveyPage class. The final page in the pager is generated by SurveyFinishPage, which tries to access the Survey associated with the FragmentPagerAdapter and pulls all of the survey answers together to display them. The Survey object is grabbed by SurveyFinishPage via a getSurvey() method in the main Activity.
Normally this works fine and the SurveyFinishPage is able to access the same Survey object that the FragmentPagerAdapter is using. If the Activity has been killed and restored, though, the SurveyFinishPage seems to still be accessing the old Survey (or maybe a copy of it) - it displays the answers from before the Activity was discarded regardless of changes to answers to the new, rebuilt Survey.
It seems like restoring the value of aSurvey in onRestoreInstanceState() in my MainActivity should establish the survey object for everything else, since MainActivity passes its Survey object to the FragmentPagerAdapter, which uses that object to make Fragments... but instead it seems that the FragmentPagerAdapter and the SurveyFinishPage are looking at two different things.
How can I restore the state of the fragments in my FragmentPagerAdapter properly so that they all reference the same Survey object?
MainActivity.java
public class MainActivity extends FragmentActivity {
SurveyPagerAdapter mSurveyPagerAdapter;
ViewPager mViewPager;
Survey aSurvey;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_poll);
if(savedInstanceState != null) {
testSurvey = savedInstanceState.getParcelable("survey");
}
else {
testSurvey = new Survey();
}
mSurveyPagerAdapter = new SurveyPagerAdapter(getSupportFragmentManager(), aSurvey);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSurveyPagerAdapter);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("survey", aSurvey);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
aSurvey = (Survey)savedInstanceState.getParcelable("survey");
}
[...]
}
SurveyPagerAdapter.java
public class SurveyPagerAdapter extends FragmentPagerAdapter {
private Survey survey;
[...]
#Override
public Fragment getItem(int i) {
Fragment fragment;
Bundle args = new Bundle();
// index 0 is the title page
if(i == 0) {
fragment = new SurveyTitlePage();
}
// final index is the finish page
else if(i == getCount()-1) {
fragment = new SurveyFinishPage();
}
// all other indices are regular poll pages
else {
args.putParcelable("question", survey.getQuestion(i-1));
fragment = new SurveyPage();
fragment.setArguments(args);
}
return fragment;
}
[...]
}
SurveyFinishPage.java
public class SurveyFinishPage extends Fragment {
private Survey survey;
[...]
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setSurvey(((MainPoll)getActivity()).getSurvey());
LinearLayout view = new LinearLayout(getActivity());
view.setOrientation(LinearLayout.VERTICAL);
Button finishButton = new Button(getActivity());
finishButton.setText("FINISH");
final TextView textView = new TextView(getActivity());
finishButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
String output = "";
for(int i=0; i<survey.getSize(); i++) {
try {
output += survey.getQuestion(i).getPrompt() + " - " + survey.getQuestion(i).getAnswer() + "\n";
} catch (Exception e) {
output += survey.getQuestion(i).getPrompt() + " - " + "no answer\n";
}
}
textView.setText(output);
}
});
view.addView(finishButton);
view.addView(textView);
return view;
}
}
SurveyPage.java
public class SurveyPage extends Fragment {
[...]
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle args = getArguments();
Question question = args.getParcelable("question");
View pageView = question.getQuestionView(getActivity(), container);
return pageView;
}
}

You could lift the Survey object to the Android application class and reference it as a singleton. That answer will likely create some debate, but it is a reasonable solution to your problem. Android guarantees there will only ever be 1 instance of your application so you can be certain (within reason) that you'll have only 1 instance of Survey.
http://developer.android.com/guide/faq/framework.html
Singleton class
You can take advantage of the fact that your application components run in the same process through the use of a singleton. This is a class that is designed to have only one instance. It has a static method with a name such as getInstance() that returns the instance; the first time this method is called, it creates the global instance. Because all callers get the same instance, they can use this as a point of interaction. For example activity A may retrieve the instance and call setValue(3); later activity B may retrieve the instance and call getValue() to retrieve the last set value.

Related

cannot restore view pager fragment state

i have a view pager with 3 fragments. i use retrofit rest api to populate each of my fragments for the first time. What i would like to achieve is when the user swipes back either in first or third fragment(those 2 fragment are being being destroyed by the view pager) to restore the data(saved in an array list) and not make a rest api call again. What i have done is to save the array list of downloaded data in onSaveInstanceState() and successfully retrieve it when the user swipes back to one of the 2 above fragments only FOR THE 1 FIRST TIME. The problem is when i navigate back to either one of the 2 fragments the specific bundle key where the array list was saved contains null value.
CompletedSurveysFragment(the third fragment):
public class CompletedSurveysFragment extends Fragment implements SAMVCView {
private static final String debugTag = CompletedSurveysFragment.class.getSimpleName();
private View view;
private RecyclerView completedSurveysRcV;
private SAMVCPresenterImpl SAMVCpresenterImpl;
private SurveysRcvAdapter surveysRcvAdapter;
private List<SurveyData> data;
public CompletedSurveysFragment() {}
public static CompletedSurveysFragment newInstance() {
return new CompletedSurveysFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.e(debugTag, "onCreateView");
if ( view == null ) view = inflater.inflate(R.layout.fragment_completedsurveys, container, false);
completedSurveysRcV = (RecyclerView) view.findViewById(R.id.completedSurveysRcV);
return view;
}
// TODO: 21/6/2016 configure Limit and offset values
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.e(debugTag, "onActivityCreated " + savedInstanceState);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
completedSurveysRcV.setHasFixedSize(true);
completedSurveysRcV.setLayoutManager(linearLayoutManager);
completedSurveysRcV.addItemDecoration(new DividerItemDecoration(ContextCompat.getDrawable(getActivity(), R.drawable.divider)));
if (savedInstanceState == null) {
SAMVCpresenterImpl = new SAMVCPresenterImpl(this);
SAMVCpresenterImpl.getSurveysBasedOnSpecificFirmId(new AllSurveysBody(getResources().getString(R.string.list_surveys), LoginActivity.getSessionPrefs(getActivity()).getInt(getResources().getString(R.string.firm_id), 0), getResources().getString(R.string.completed), 8, 0));
surveysRcvAdapter = new SurveysRcvAdapter(null, completedSurveysRcV);
completedSurveysRcV.setAdapter(surveysRcvAdapter);
} else {
//Log.e(debugTag, savedInstanceState.+"");
if (savedInstanceState.getParcelableArrayList("data") != null) {
Log.e(debugTag, "here "+ savedInstanceState);
surveysRcvAdapter = new SurveysRcvAdapter(savedInstanceState.<SurveyData>getParcelableArrayList("data"), completedSurveysRcV);
completedSurveysRcV.setAdapter(surveysRcvAdapter);
surveysRcvAdapter.notifyDataSetChanged();
}
//Log.e(debugTag, getArguments().getParcelableArrayList("data")+"");
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList("data", (ArrayList<? extends Parcelable>) this.data);
Log.e(debugTag, "CompletedFragment onSaveInstanceState "+ outState);
}
#Override
public void onSuccessSurveysFetched(List<SurveyData> data) {
this.data = data;
surveysRcvAdapter = new SurveysRcvAdapter(data, completedSurveysRcV);
completedSurveysRcV.setAdapter(surveysRcvAdapter);
surveysRcvAdapter.notifyDataSetChanged();
}
#Override
public void onFailure() {
}
}
View pager adapter:
public class SurveysPagerAdapter extends FragmentStatePagerAdapter {
private static final String debugTag = SurveysPagerAdapter.class.getSimpleName();
private List<SurveyData> data;
String[] tabText;
public SurveysPagerAdapter(FragmentManager fragmentManager, String[] tabText) {
super(fragmentManager);
this.tabText = tabText;
}
#Override
public Fragment getItem(int position) {
Log.e("SurveysPagerAdapter", position+"");
switch (position) {
case 0:
return CompletedSurveysFragment.newInstance();
case 1:
return OngoingSurveysFragment.newInstance();
case 2:
return PendingSurveysFragment.newInstance();
default:
return null;
}
}
#Override
public CharSequence getPageTitle(int position) {
return tabText[position];
}
#Override
public int getCount() {
return 3;
}
}
Your issue is that you're always returning a new instance of your fragment. Instead of calling CompletedSurveysFragment.newInstance(); (and your other Fragments) every time user swipes, create an array of fragments and retrieve it this way:
...
Fragment [] pages = new Fragment[getCount()];
...
#Override
public Fragment getItem(int position) {
Log.e("SurveysPagerAdapter", position+"");
switch (position) {
case 0:
if(pages[position] == null)
pages[position] = CompletedSurveysFragment.newInstance();
return pages[position];
...
}
Then, you can fetch and cache your data in onCreate() and retrieve it later in onResume() in your respective fragments.
I think onPause() and onResume() won't work. Fragments are tied to their parent activity so since you browse through fragments parent activity is on an onResume() status. What I suggest you to do is to use singleton objects to fetch and store your data. Each fragment can keep a reference to the respective object and have instant access to the data you need. There is plenty of info about singleton pattern and how it works.
The reason this is happening is because onSaveInstanceState only occurs when the parent activity is closed. Since the parent activity of your viewpager is still active when you switch between your fragments, onSaveInstanceState will not be called.
To get the data to save like you are intending, what I would likely do instead is save the data in onPause() and retrieve the data in onResume().
EDIT
According to the docs you need to put the call to super.onSaveInstanceState(savedInstanceState); after you modify the Bundle.
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}

Getting mixed data when using EventBus in a ViewPager

I am using EventBus to post the result to a fragment when an http request is made successfully. This works nice when there's a one subscriber and one publisher relation.
However, in my application I have a screen that uses a ViewPager with tabs. And because the pages are very similar, I use the same fragment with a different parameter corresponding to each tab, to download data.
The Fragment looks something along these lines:
public class MyFragment extends Fragment{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getDefault().register(this);
}
public void onEvent(ServerResponse response) {
updateUi(response);
}
#Override
public void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
}
And you might guess already what happens when data is received.
Since the are many subscribers with the same signature, waiting a ServerResponse, the responses don't go to the corresponding tab, but the same response is received and displayed in every fragment, and the data gets mixed.
Do you have any idea how to solve this?
Hei! Same problem here, but I have a solution.
The problem is that you have a lot of Fragments (instances from same object) and all of them are listening the same event, so all of them are updated when you post an event.
When you post an event, try send a position and when you instantiate your Fragment you need to store the page adapter position. After just check if the event has the same position of your Fragment.
For example:
public static QuestionFragment newInstance(int position) {
QuestionFragment fragment = new QuestionFragment();
Bundle args = new Bundle();
args.putInt(ARG_POSITION, position);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
vMain = inflater.inflate(R.layout.fragment_question, container, false);
EventBus.getDefault().post(new GetQuestionEvent(mPosition));
return vMain;
}
public void onEvent(GetQuestionEvent e) {
if (e.getQuestion().getPosition() == mPosition) {
TextView tvPostion = (TextView) vMain.findViewById(R.id.tv_position);
tvPostion.setText("" + e.getQuestion().getPosition());
}
}

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
}
}

FragmentAdapter doesn't hold the good reference of the fragment

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.

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.

Categories

Resources