In my activity I have a check for savedInstanceState, making sure I am not creating multiple fragments
But my question is should I have similar checks in Fragment's onCreate() and onCreateView()
Because when I rotate screen Fragment's onCreate() and onCreateView() are called everytime.
Question is, Is it OK for these 2 methods to re-do there job after everyscreen rotation or they should have a savedInstanceState check as well.
Right now my onCreate() makes a service call and onCreateView inflates a view (Recyclerview)
When an activity or Fragment is recreated, the onCreate() method is first fired, followed by the onRestoreInstanceState() method, which enables you to retrieve the state that you savedpreviously in the onSaveInstanceState() method through the Bundle object in its argument:
# Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//---retrieve the information persisted earlier---
String ID = savedInstanceState.getString(“ID”);
}
Related
When my activity containing viewpager is killed by system in background and then restores its state, fragments are correctly created and viewpager adapter can also point to them correctly.
But when I get a fragment reference and try to access its fields, they are all null (checked by using breakpoint).
I checked this by placing breakpoints in fragment onCreateView() and in my activity button's clickListener.
((WelcomeFragment)homeActivityFragmentPageAdapter.getItem(POSITION_HOME)).setdata(myData);
Now this method will through null pointer exception since setdata(data) is internally accessing arraylist field of fragment.
This creates a problem for me since, my activity has to continuously feed network data to the fragment by calling its public method (as suggested by documentation).
How to insure that after state restored; correct instance is pointed in my activity.
Try to use instantiateItem adapter method instead getItem.
((WelcomeFragment)homeActivityFragmentPageAdapter.instantiateItem(mViewPager, POSITION_HOME)).setdata(myData);
Method getItem is overrided method, and common use is creation of child fragments.
EDIT:
In case of the question's scenario, you also need to store the state of FragmentStatePagerAdapter manually:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState
.putParcelable("pages",homeActivityFragmentPageAdapter.saveState());
super.onSaveInstanceState(savedInstanceState);
}
Then you can retrieve the state in oncreate:
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
homeActivityFragmentPageAdapter.restoreState(savedInstanceState.getParcelable("pages"),this.getClassLoader());
welcomeFragment = (WelcomeFragment) homeActivityFragmentPageAdapter.instantiateItem(mViewPager, POSITION_HOME);
}
else { //simply create a new instance here}
homeActivityFragmentPageAdapter.addFragmentToAdapter(welcomeFragment);
homeActivityFragmentPageAdapter.notifyDataSetChanged();
}
I have an Activity called BaseActivity, hosting multiple fragments.
The BaseActivity has a public field Object owhich is accessed by the fragments by calling Object o = ((BaseActivity) getActivity()).o; This is initialized in the fragments onCreate.
This works but I have problems with runtime configuration changes. It seems that the Fragments onCreate is called before the BaseActivitys onCreate, so I cant retain the Object from the Bundle i saved in onSaveInstanceState.
Is there a way I can make sure the acitivty can retain its object from the saved Bundle before the Fragment tries to access it?
Try this ..
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Object o = ((BaseActivity) getActivity()).o;
}
This makes sure that the activity's onCreate has completed executing.
I have two different activities, in the first one I enter some info into some EditTexts, I then go to the second activity, but when I return, the text that was on EditTexts in the first activity are gone.
Here is the OnCreate() for the first activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_frm_recetas);
txtClient = (EditText) findViewById(R.id.txtNombreCliente);
if(savedInstanceState != null){
String client = savedInstanceState.getString("Client");
txtClient.setText(client);
}
}
I'm using the onSaveInstanceState method to save the info
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
String x = txtClient.getText().toString();
savedInstanceState.putString("Client", x);
super.onSaveInstanceState(savedInstanceState);
}
When doing a debug, I can see the savedInstanceState Bundle has indeed been filled in the onSaveInstanceState method, but in the OnCreate in shows null.
Maybe I have to add something in the second activity? I currently don't have anything in there other than a button that takes me back to the first activity.
You need to call super.onSaveInstanceState(savedInstanceState); as the first line in onSaveInstanceState method.
Next you need to put
if(savedInstanceState != null) {
String client = savedInstanceState.getString("Client");
txtClient.setText(client);
}
into the onRestoreInstanceState method. onCreate is only called when re-drawing the app.
It shows null because onCreate is called only when that activity is first created, when you return back from the second activity, it resumes your first activity..try showing it on onResume() method
My guess is that the first activity hasn't been destroyed, so onCreate is never called when you navigate back to first activity
I guess onCreate is called when aactivity is going to load into memory, and at that time activity does not contain any thing . thats why it always return null.
to save data you have onsaveinstance method and to restore you have onrestoreinstance method.
onSaveInstanceState() is a method used to store data before pausing the activity.
onRestoreInstanceState() is method used to retrieve that data back.
I have a fragment attached to the activity using XML (and setContentView() in activity). A have a problem because I have very dynamic views in my fragment, so when orientation changes
I must restore all states of views.
I have problem because I'm using something like that:
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("restore", true);
outState.putInt("nAndroids", 2);
}
But after orientation change when methods with param Bundle savedInstanceState are called (like onCreateView etc) my savedInstanceState is always null.
I'm not a noob in the Android but now I'm very angry because of this problem...
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (savedInstanceState == null) {
//smth
} else {
// smthelse THIS IS NEVER REACHED BECAUSE BUNDLE IS ALWAYS NULL
}
getListView().setDivider(getResources().getDrawable(R.drawable.list_divider));
}
All the problem was in that I don't declare android:id for the fragment in XML. Android needs ID or TAG to recognize stored fragment and reproduce all elements in it. So guys, remember - every instance of fragment needs unique id or tag!
Also, when setRetainInstance(true) is declared then bundle should always return null.
I had a similar problem where I was always getting savedInstanceState as null inspite of supplying the bundle to the Fragment.
The only solution that worked for me was to do
myFragment.setArguments(bundle)
with my bundle from the Activity and do a
Bundle bundle = this.getArguments();
in onCreateView of the fragment.
Hope this helps someone else.
For Fragment :-
use this for save state of fragment on orientation.
onCreate(Bundle save)
{
super.onCreate(save);
setRetainInstance(true);
}
See this tutorial :-
http://techbandhu.wordpress.com/2013/07/02/android-headless-fragment/
For Activity:-
When you start your application, in onCreate, your bundle object is null, so you have to put a check like below and when you rotate your screen then onSaveInstance is called and your bundle object is initialized
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
if (savedInstanceState != null) {
boolean t = outState.getBoolean("restore");
int s = outState.getInt("nAndroids");
}
}
First you should put your data, then call super.onSaveInstanceState(outState);
public void onSaveInstanceState(Bundle outState) {
outState.putBoolean("restore", true);
outState.putInt("nAndroids", 2);
super.onSaveInstanceState(outState);
}
And be sure that activity has not nohistory property in AndroidManifest.xml or set it to false.
<activity
android:noHistory="false">
If you are trying to use outState to save the state and destroy the fragment by navigating to another fragment, it will not work, you have in this case to save your state permanently in either sharedPreferences or if it's big and you want to be more organized you can use any persistence lib like Room, Realm, ...etc.
When should use outState and savedInstanceState only to make Fargment/Activity survive config change(rotation for example) or processes being killed by the OS when the app is in background for example.
Ok I know this is an old post but I couldn't find the right answer for me here nor many other places, so I am posting how I fixed my case.
So My Fragment is inside an Activity. And I originally tried to save Bundle only in Fragment and retrieve it at onCreateView. However that was the problem.
I fixed this by initiating myFragment object in activity and put that object to activity Bundle at onSaveInstanceState(). Then retrieved it at onRestoreInstanceState(). I used getSupportFragmentManager().putFragment/getFragment. Then the savedInstanceState in fragment was no longer null.
In a application whenever a fragment loses focus (i.e. another activity / fragment is opened over it), it's onSaveInstanceState() is called.
Same is mentioned in developers guide.
I'm trying to use this approch to maintain the state of my fragment whenever it is resumed.
My intention was to call this bundle in onActivityCreated(), when the fragment is resumed.
Although onSaveInstanceState is called before fragment losing focus.
But, when onActivityCreated() is called it recives the Bundle savedInstanceState as null.
How can I fetch the data from the bundle.
Code:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
MyListAdapter adapter = new MyListAdapter(getActivity(),
R.layout.my_row, titles, icons, this);
setListAdapter(adapter);
if (savedInstanceState != null) {
// Never goes inside this condiiton.
// Restore last state for checked position.
mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
Then it means that your activity and fragment were just paused and did not have to save their instance state (onSaveInstanceState() is not necessarily called).
If you want to make sure onSaveInstanceState() is called, select "Don't keep activities" in the device's developer settings. Then each time an activity is paused, the system kills it forcing the call to onSaveInstanceState() (except when you just press back of course)