android-how to save dada when activity re-created - android

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.

Related

Issue in using onStop() and onResume()

I am using onStop() to save a boolean value which I need when the activity resumes.
Here is my code:
#Override
protected void onStop()
{
super.onStop();
Bundle bundle = new Bundle();
bundle.putBoolean("value",value);
getIntent().putExtras(bundle);
}
#Override
protected void onResume()
{
super.onResume();
if(getIntent().getExtras() != null)
{
Bundle bundle = getIntent().getExtras();
value = bundle.getBoolean("value");
}
}
My issue is no matter what the value of the boolean is, my onResume() always retrieves it as FALSE. This issue only occurs if I leave my activity using the BACK button. If I press home, things seem to work fine(i.e if the boolean was TRUE then onResume() retrieves it as TRUE.
Please do help me because I don't understand why onResume() always gets the value of the boolean as FALSE even when I save it as TRUE in onStop().
I also tried onRestart(), onPause() and onBackPressed() but I still can't get the proper boolean value to be saved.
You have two issues here.
the correct way to save values during activity destruction is to use onSaveInstanceState(Bundle) and get the value from the Bundle passed to onCreate(Bundle).
Check example below:
public class SavedInstanceExample extends AppCompatActivity {
private boolean myBoolean;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_savded_instace_example);
if (savedInstanceState != null) {
myBoolean = savedInstanceState.getBoolean("key");
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("key", myBoolean);
}
}
When you press the back button the activity will be finished. That means completely gone. And values saved one the methods explained above will not be there.
The way to save something to survive the Activity being finished is to save it to the disk. One common/simple way to do it is using the SharedPreferences
When the Android application opens the following activity lifecycle methods will be called.
onCreate();
onStart();
onResume();
and when you press the back button, the application will be destroyed by calling following methods
onPause();
onStop();
onDestroy();
And in the second case when you press home button the following methods will be called
onPause();
onStop();
That means your application is not destroyed completely and you can open it from recent apps so that the activity re-appears by calling
onStart();
onStop();
That is why your code works in this case.
Activity gives onSavedInstanceState() method to save your data during configuration changes or something else.
Here is the link for Android documentation for
Activity
I would suggest you to read the Google Developers Link for Activity documentation.Google Developers Activity
The OP's code is basically right. onSavedInstanceState is no good if you are not destroying the activity but, for example, replacing a fragment in an activity with another fragment and then returning to it, in which case you have to use onStop and onResume as follows. This is Kotlin and it works but the principle is the same.
override fun onStop() {
super.onStop()
val bundle = Bundle()
bundle.putBoolean("BOOL", false)
activity?.intent?.putExtras(bundle)
}
override fun onResume() {
super.onResume()
if (activity?.intent?.extras != null) {
val bundle = activity?.intent?.extras
val bool = bundle?.getBoolean("BOOL")
println("BOOL is $bool")
}
}
My Java's a bit rusty but I suspect the OP's problem might have been that he mixed up boolean and Boolean?

onSaveInstanceState always return null

I'm still working on my app, and I have a new issue.
On my WarikeActivity I have a button, this button send me to a MapActivity and then I want to get back to my WarikeActivy with some values from the MapActivity, I tried this:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putByteArray("byte_warike", byteArray);
super.onSaveInstanceState(savedInstanceState);
}
And then of course
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
byteArray = savedInstanceState.getByteArray("byte_warike");
foto = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
imgFoto.setImageBitmap(foto);
}
But the app crash because byte_array is always null. Any idea about how to solve it?
I was reading others posts by I cant solve that problem yet.
Thanks in advance.
OnSaveInstanceState and onRestoreInstanceState should actually only be used when the activity is being recreated and wants to save some info about itself.
You, on the other hand, want to send info to the previous activity.
Reto Meier (a Google employee working on Android) has given a perfect response how this could be done here: How to pass the values from one activity to previous activity

onRestoreInstanceState is never called / savedInstanceState is always null

I have looked in all the site and I don't understand why it's not working on my side.
Please find my source code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
Log.e("EVERYTHING", "OK");
}
}
and
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("test", "titi");
Log.e("Save", "titi");
super.onSaveInstanceState(outState);
}
I launch my appli, then press the home button, then restart my phone and launch the appli again, but the savedInstanceState is null.
Could you please help me.
Regards
onSaveInstanceState is used to persist state in memory so it's not suitable for situations like you described above. If you restart your phone, obviously all state store not persistently (only in memory) is not preserved.
If you want to store state this way, you should look at something persistent, e.g. shared preferences or SQLite.

onResume() is not called in physical device instead onCreate() is called

Iam little bit amazed with this.I have an onResume() in my activity.Its called and works well in my emulator, but in a physical device samsung galaxy note for specific with jellybean installed,its not called.Instead onCreate() is called all the time.Why this happens?
public void onResume(){
super.onResume();
if(firsttime){
try {
Toast.makeText(getApplicationContext(), "Resuming Activity",Toast.LENGTH_LONG).show();
addReminder();
} catch(Exception exception) {
exception.printStackTrace();
}
} else {
firsttime=true;
}
}
This is my code.firsttime is a static boolean variable.It is used to prevent onResume() being called when app is started for the first time
Considering your current scenario, you should save variable in preferences instead of relying on activities lifecycle since lifecycle depends on many things.
Using static variable for this scenario is bad choice in general.I think this should solve your problem.
Try to print something inside the onResume and check it in LogCat.... the code inside onResume may be causing this.
or else can you elaborate your question?
I think here is what happens,
when your app not the Top app, the activity manager actually destroy the activity, it only called
public void onSaveInstanceState(Bundle savedInstanceState)
no
onStop
called, so no
noResume
will be called.
The correct to do this is, when put all states of this activity when
public void onSaveInstanceState(Bundle savedInstanceState)
called.
and in your onCreate() function, do such thing
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Always call the superclass first
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
} else {
// Probably initialize members with default values for a new instance
}
...
}
to check if you have some saved state.
Most code was copy from android developer site:
http://developer.android.com/training/basics/activity-lifecycle/recreating.html

How to maintain DatePicKer State After Rotate Screen

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.

Categories

Resources