Reputation: 774
I am working on a Android application where in I want to save the information entered into the textviews of the activity in the database whenever the phone call arrives, orientation of the app is changed, etc.
I am using this code to save the information entered into the textview by the user.
@Override
protected void onSaveInstanceState(Bundle outState) {
save();
Toast.makeText(getApplicationContext(), "On save state", Toast.LENGTH_SHORT).show();
super.onSaveInstanceState(outState);
}
Problem :
Whenever my phone orientation is changed the onSaveInstanceState
method is called twice. Can anyone explain me the reason for this.
Because it is called twice, save()
also get called twice and I have duplicate entries into my database table - which is not good.
I cannot use android:configChanges="orientation|screenSize"
in manifest file to deal with orientation change. As it makes the ads disappear when user changes landscape to portrait.
onSaveInstanceState
is called only once when phone call is received :)
Note : save() is also called onBackPressed() method
Please assist !
Upvotes: 1
Views: 2147
Reputation: 10038
In my case, it was getting called twice when returning from camera intent + orientation change. Then i ended up writing Singleton Manager class to save and restore my variables whenever i want. This class holds your variables in static final
variables and you should clear it when you no longer use it.
Upvotes: 0
Reputation: 1477
First, make sure that what you really want to do is saving persistent data in a database. If so, onSaveInstanceState
is not your method.
onSaveInstanceState
is used to save the temporary state of the activity to be able to recreate it exactly as it was on the onCreate
or onRestoreInstanceState
. The default implementation already saves/restores most of the UI standard views and if you override it probably you will want to keep calling the default implementation and then save/restore the additional values. By the way, the values are stored on the Bundle which basically provides a way to store/retrieve key-value pairs.
If you really want to save persistent state, you should do it on the onPause
method that is part of the lifecycle of the Activity
. Note what the activity documentation says:
Note that it is important to save persistent data in onPause() instead of onSaveInstanceState(Bundle) because the latter is not part of the lifecycle callbacks, so will not be called in every situation as described in its documentation.
To avoid the problem with duplicate rows, you just need to check if the record you are trying to save already exists or not (you need some kind of unique identifier for this) and then create or update accordingly.
Upvotes: 1