I have implemented the Demo version of HelloDatePicker provided by the API.
http://developer.android.com/resources/tutorials/views/hello-datepicker.html
However I cannot maintain its value after rotating the screen. Can someone post an example or indicate how one can do this.
Thanks
Use onRetainNonConfigurationInstance() to save the date, and in onCreate use getLastNonConfigurationInstance() to load and set the date.
Even without a Fragment, the Activity alone can do this:
#Override protected void onSaveInstanceState (Bundle outState)
{
super.onSaveInstanceState (outState);
outState.putInt ("YEAR", mDatePicker.getYear ());
outState.putInt ("MONTH", mDatePicker.getMonth ());
outState.putInt ("DAY", mDatePicker.getDayOfMonth ());
}
#Override protected void onRestoreInstanceState (Bundle savedInstanceState)
{
super.onRestoreInstanceState (savedInstanceState);
mDatePicker.updateDate (savedInstanceState.getInt ("YEAR"),
savedInstanceState.getInt ("MONTH"),
savedInstanceState.getInt ("DAY"));
}
After rotation, Activity is recreated. The simplest way to avoid it is to add:
android:configChanges="keyboardHidden|orientation"
in AndroidManifest.xml in Activity declaration.
For more information you should read it.
Related
I have an activity in my android app that calls an asynctask on onCreateView()
Here is my code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weeklyprofit);
fromDateTxt=(TextView)findViewById(R.id.fromDate);
toDateTxt = (TextView)findViewById(R.id.toDate);
GetXYPoints getXY = new GetXYPoints();
getXY.execute(fromDateTxt.getText().toString(),toDateTxt.getText().toString());
}
now my application needs to rotate, so i need to store data when rotate :
I have implemented this as below :
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("from", fromDateTxt.getText().toString());
savedInstanceState.putString("to", toDateTxt.getText().toString());
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
SystemClock.sleep(500);
fromDateTxt.setText(savedInstanceState.getString("from"));
toDateTxt.setText(savedInstanceState.getString("to"));
GetXYPoints getXY = new GetXYPoints();
getXY.execute(fromDateTxt.getText().toString(),toDateTxt.getText().toString());
}
So i recall the asynctask again with restored data, my problem is that the activity run again when rotate and the it calls onRestoreInstanceState so how can i prevent the activity from calling the first asyncktask?
In other way what is the best solution to store data returned by an asynck task when screen is rotate?
i would suggest you to to make sure you actually need your activity to be reset on a screen rotation (the default behavior). Every time I've had issues with rotation I've added this attribute to my tag in the AndroidManifest.xml, and been just fine.
android:configChanges="keyboardHidden|orientation"
source How to handle an AsyncTask during Screen Rotation?
In your AndroidManifest.xml add following for prevent reloading activity when orientation change
android:configChanges="orientation|screenSize"
So, you'll have something like this:
<activity android:name="Activity"
android:configChanges="orientation|screenSize">
</activity>
Hope it works!
I'm moving from activity 1 to activity 2 and send some data via intent .
It's ok and no problem ,but when I leave activity 2 and then come back , the intent is empty . For solving this problem I've tried this code :
#Override
protected void onSaveInstanceState (Bundle outState) {
outState.putInt("row_id", row_id);
}
#Override
protected void onRestoreInstanceState (Bundle savedInstanceState) {
int row_idss = savedInstanceState.getInt("row_id");
Log.v("this","restore" + Integer.toString(row_idss));
}
I tried to save it before I leave the activity and retrieve it on re-open .anyway , It didn't work and didn't log it either.
I tried onPause and onResume , strangely they didn't call either . I used this code to make sure it runs
#Override
protected void onResume() {
super.onResume();
Log.v("this","test");
}
nothing logged .
Could you help me to solve this problem ? I don't know what should I do to solve it
thanks so much
You are missing the calls:
super.onSaveInstanceState(outState);
super.onRestoreInstanceState(savedInstanceState);
Check the answer of this question, in this answer they're not using the method onRestoreInstanceState but just the onCreate to restore the data. You also could use onRestoreInstanceState if you need a different behaviour.
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.
I have an activity with action bar tab. Each tab contain a fragment. Now when I rotate my device, bundle in my corresponding fragment is coming as null. This is taken care when I using device post android 3.2, but it is happening when device is Andoird3.0. I am having a headache after working on this issue. I crossed check various link on SO, but no help. Although I have given enough details, still will provide some code snippet as at various cases user ask for code snippet.
In my fragment class I am storing this value
#Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putBoolean("textboxVisible", true);
}
this is storing one boolean variable which it retrived as below.
/**
* Function called after activity is created. Use this
* method to restore the previous state of the fragment
*/
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null)
{
//restore the state of the text box
boolean textboxVisible = savedInstanceState.getBoolean("textboxVisible");
if (textboxVisible)
{
//do some stuff
}
}
}
but after rotation savedInstanceState is coming as null.
I don't what is going wrong. I have read in some document that below 3.2 the onCreateView() of
fragment is not called with bundle value. But to deal with this. Any help will be appreciated.
if you use setRetainInstance(true) the savedInstance bundle is always gonna be null after orientation changed. SO you cannot really save something with it, but what you can do if you need to save something, is to put it in a data member of the fragment, because setRetainInstance(true) preserves the fragment and doesn't destroy it, so after the device was rotated you gonna have the same values.
Try to get the savedInstanceState in onCreate of the Fragment.
Like
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
if (savedInstanceState != null) {
// IT MUST NOT BE NULL HERE
}
}
Please try... i hope it will work
If you create the app described in this tutorial http://developer.android.com/resources/tutorials/views/hello-datepicker.html
change the date, and then rotate the device, you will notice the following:
The app's textview date resets as expected (since the activity is destroyed and recreated), but if you then hit the "change the date" button, the date that you set prior to the rotation is retained. The SDK documentation discourages using onConfigChanged="orientation|screenSize" to catch the orientation change, so my question is: what is the "best" way to keep the datepicker's default consistent with the member variables that are used in one's app? I don't much care if the values of the member variables get retained, or if the picker gets reset to today's date along with them, but the inconsistency looks sloppy to me.
You can save your DatePickerDialog member variables in onSaveInstanceState, then restore them on onCreate. Something like:
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("day", mDay);
outState.putInt("month", mMonth);
outState.putInt("year", mYear);
}
To complete the above answer, you would probably do something like this, as shown here (override the two methods below in your Activity):
https://stackoverflow.com/a/54283814/5916188
#Override protected void onSaveInstanceState (Bundle outState)
{
super.onSaveInstanceState (outState);
outState.putInt ("YEAR", mDatePicker.getYear ());
outState.putInt ("MONTH", mDatePicker.getMonth ());
outState.putInt ("DAY", mDatePicker.getDayOfMonth ());
}
#Override protected void onRestoreInstanceState (Bundle savedInstanceState)
{
super.onRestoreInstanceState (savedInstanceState);
mDatePicker.updateDate (savedInstanceState.getInt ("YEAR"),
savedInstanceState.getInt ("MONTH"),
savedInstanceState.getInt ("DAY"));
}