Reputation: 71
I need that when calling the onBackPressed
method, the activity is not destroyed but pauses and stops.
My idea is that it works like when the Home button of the mobile is pressed, which calls onPause
and onStop
because that way, the activity is not destroyed and when the activity is reopened, onResume
is called so that the variables remain the value that when the activity was closed.
Is there any way to do this? If not, is there a way to keep the state of the variables once the activity is closed? I have tried to use SharedPreference but I cannot use them because my variables are of different types than those offered.
Upvotes: 0
Views: 256
Reputation: 311
If you want to customize the behaviour of your buttons, you have to use in your activity ...
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK){
return true; //To assess you have handled the event.
}
//If you want the normal behaviour to go on after your code.
return super.onKeyDown(keyCode, event);
}
Here is some more information about handling key event.
Although it seems what you want to do is just retain the state of your activity. The best way is to store your data before quitting and call it back when you recreate your activity.
If you want to store temporary data (I mean not save it between 2 boots), one way to do it would be to use sharedPreferences.
//Before your activity closes
private val PREFS_NAME = "kotlincodes"
private val SAVE_VALUE = "valueToSave"
val sharedPref: SharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
val editor: SharedPreferences.Editor = sharedPref.edit()
editor.putInt(SAVE_VALUE, value)
editor.commit()
//When you reopen your activity
private val PREFS_NAME = "kotlincodes"
val sharedPref: SharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
sharedPref.getString(SAVE_VALUE, null)
Another way to do it since you cannot use sharedPreferences (because you don't use primitive types), is to use a global singleton.
Here is a Java implementation ...
public class StorageClass{
private Object data1 = null;
private StorageClass instance;
private StorageClass(){};
public static final StorageClass getInstance(){
if(instance == null){
synchronized(StorageClass.class){
if(instance==null) instance = new StorageClass();
}
}
return instance;
}
public void setData1(Object newData) { data1 = newData; }
public Object getData1() { return data1; }
}
Then just use ...
StorageClass.getInstance().setData1(someValue);
... and ...
StorageClass.getInstance().getData1(someValue);
In Kotlin ...
object Singleton{
var data1
}
Which you use with ...
Singleton.data1 = someValue //Before closing.
someValue = Singleton.data1 //When restarting the activity.
Upvotes: 1