I am creating a calculator application, when my activity is sent to background and then brought to front.The result in it becomes zero. How can i save the data nd retrive it next time hen activity is recreated.
For that specific case, you want to use the Activity lifecycle methods onSaveInstanceState and onRestoreInstanceState. Override both those methods, and then save the necessary data in onSaveInstanceState. In the onCreate or the onRestoreInstanceState check for the existence of the saved data and then restore it to the right place.
Note: you can use preferences or a database as well, but those are generally to be used for data that should last more than a single background/restore cycle. The onSaveInstanceState/onRestoreInstanceState methods are specifically for the case where an Activity gets sent to the background and then restored later.
Use SharedPreferences like :
SharedPreferences preferences = null;
SharedPreferences.Editor editor = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
}
in onDestory() write :
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
editor = preferences.edit();
editor.putInt(YOUR_KEY, YOUR_VALUE);
editor.commit();
}
and in onStart() write :
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
int result = preferences.getInt(YOUR_KEY, YOUR_VALUE);
}
Hope this will help you
Related
I have two activities. In the first activity, I have a SharedPreferences with a TextView, which displays the amount of data in the SharedPreferences. These codes are written in the onCreate()
SharedPreferences coin = getSharedPreferences("saved", MODE_PRIVATE);
SharedPreferences.Editors editor2 = coin.edit();
editor2.putInt("t", 0).apply();
editor.commit();
TextView name = (TextView) findViewById(R.id.textview);
Integer a = coin.getInt("t", 0);
name.setText(a.toString());
In the second activity, I wanna add 10 points to the data and update the SharedPreferences. These codes are not inside onCreate().
SharedPreferences coin = getSharedPreferences("saved", MODE_PRIVATE);
SharedPreferences.Editors editor2 = coin.edit();
int a = coin.getInt("t", 0);
int b = a + 10;
editor2.putInt("t", Integer.valueOf(b));
The problem is, after adding 10 units there is no update in the TextView so I don't even know if the 10 units have been added correctly to SharedPreferences or not.
Please help
If I understand, you would like reflect the final value of t in SharedPreference in your first activity after its updated in second activity?
To do that, create a function updateNameTV() which would contain logic to update the TextView with the value of t from SharedPreference
and call that function in onResume() of the FIRST activity like:
#Override
protected void onResume() {
// TODO Auto-generated method stub
updateNameTV();
super.onResume();
}
So when Activity 2 is launched, Activity 1 goes in back of the stack and onPause() gets called.. when we return to Activity 1 this activity is pop back and onStart() followed by onResume() is called.
These are the lifecycle events more here
So the plan is, when onResume() is called we update the TextView value with the latest SharedPreference
And we do that before calling super.onResume() such that update is performed before handing over the control to next lifecycle event. Hope this gives more clarity.
You have to register OnSharedPreferenceChangeListener in your first activity in order to listen to the changes and then update your TextView with the updated value.
Implement OnSharedPreferenceChangeListener in your FirstActivity:
public class FirstActivity extends AppCompatActivity implements
SharedPreferences.OnSharedPreferenceChangeListener {
...
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
// This method will be called when there is a change in SharedPreference
// Update your textview here
if(s.equals("t")) {
Integer a = sharedPreferences.getInt("t", 0);
name.setText(a.toString());
}
}
}
In your FirstActivity's onStart() and onStop() method, manage the listener:
#Override
protected void onStart() {
super.onStart();
getSharedPreferences("saved", MODE_PRIVATE).registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onStop() {
getSharedPreferences("saved", MODE_PRIVATE).unregisterOnSharedPreferenceChangeListener(this);
super.onStop();
}
But remember, once you leave your FirstActivity, the listener gets unregistered and you will no longer receive updates. To reflect the updates even after the activity go background, you can just update your textview in your onStart() so that when the FirstActivity starts, the textview gets updated with the latest value from SharedPreferences:
#Override
protected void onStart() {
super.onStart();
SharedPreferences coin = getSharedPreferences("saved", MODE_PRIVATE);
coin.registerOnSharedPreferenceChangeListener(this);
// Also Update the textview here
Integer a = coin.getInt("t", 0);
name.setText(a.toString());
}
Now, any update to the preference from anywhere will also change the textview text as soon as the FirstActivity comes into foreground or launches.
I'm trying to save a TextView value that changes on a button click and keep it stored until I kill the app.
I am trying to use onSaveInstanceState and onRestoreInstanceState to save and restore as long as the app is running. It doesn't work for me. Here is my code.
TextView questionText;
Button button ;
String perso1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
perso1 = MainActivity.perso;
questionText = (TextView)findViewById(R.id.perso);
questionText.setText(perso1));
getSupportActionBar().setIcon(R.drawable.ic_back_icon);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(R.string.settings);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
resetConsent();
questionText.setText("You clicked on the button");
}
});
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
String newtext = questionText.getText().toString();
outState.putString("TEXT", newtext);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);
questionText.setText(savedInstanceState.getString("TEXT"));
}
I'm trying to keep the new value of textview when I click on the button until I kill the app. What am I doing wrong?
ViewModel is what you need!
Why
The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations.
It makes your life easier. You don't need to think on how to save it in youe savedInstanceState, but you can just store the String in your ViewModel (as a LiveData), then observe it.
With LiveData, you can change the value everytime the button clicked, and observe the value everytime it changes.
You can always try to save state in a different way.
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
String newtext = questionText.getText().toString();
outState.putString("TEXT", newtext);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
//check if there was a previous saved state
if(savedInstanceState != null){
//get the value you stored earlier in onSaveInstanceState()
perso1 = savedInstanceState.getString("TEXT");
}
questionText = (TextView)findViewById(R.id.perso);
questionText.setText(perso1));
//....
}
But this is just another way to save state.
I think i your error is explained below.
//you did this correctly- look, you set questionText here
onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
//set the questionText below
questionText.setText(savedInstanceState.getString("TEXT"));
}
but then in onCreate() you set the questionText again. This time to an incorrect value.
perso1 = MainActivity.perso;//< -- setting perso1 to nothing?
questionText = (TextView)findViewById(R.id.perso);
questionText.setText(perso1));//<-- setting questionText again
onRestoreInstanceState
This method is called between onStart() and onPostCreate(Bundle).
In onSaveInstanceState() you did it correctly, in onRestoreInstanceState() you did it correctly, in onCreate() you set the value again to the wrong value.
Additionally read this when deciding to keep saving state this way or using a ViewModel
For simple data, the activity can use the onSaveInstanceState() method and restore its data from the bundle in onCreate(), but this approach is only suitable for small amounts of data that can be serialized then deserialized, not for potentially large amounts of data like a list of users or bitmaps.
Am trying to implementent onPause() and onResume(), such that when am out of the activity the the text in my text view is still there, but its displaying "null" when i start the the activity please assist!
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
etPassenger.setText(""+ gotPassenger );
etStaffNumber.setText("" + gotStaffNumber);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
etPassenger.setText(""+ gotPassenger );
etStaffNumber.setText("" + gotStaffNumber);
}
I think gotPassenger and gotStaffNumber vars are null - if you want to save them than you have to use prefs or save them to some bundle to restore later.
When you are minimizing your activity your variables becoming null.
Add the following code in your activity,
#Override
public void onSaveInstanceState(Bundle savedInstanceState)
{
savedInstanceState.putString("gotPassenger",gotPassenger);
savedInstanceState.putString("gotStaffNumber",gotStaffNumber);
}
And, in your onCreate() method, add the following,
if(savedInstanceState!=null)
{
etPassenger.setText(savedInstanceState.getString("gotPassenger"));
etStaffNumber.setText(savedInstanceState.getString("gotStaffNumber"));
}
When you are leaving your activity, you will loose the data stored inside gotPassenger and gotStaffNumber.
If you want to reuse them after exiting your application, you have to use SharedPreferences to save them first and retrieve them when you are back.
If you want to save your data even when closing your app you need to use sharedPreferences. Here's how you use them
I have application with an activity and a service, I need to save some value in the activity and retrieve in the service.
i could save the value using SharedPreferences in the activity, however, when I try to retrieve the value in the BroadcastReceiver, it says getPreferences is undefined for service.
how could I retrieve my value in BroadcastReceiver?
EDITED to reflect change of the original question from Service to BroadcastReceiver.
Instead of using getPreferences(int mode) in the Activity use...
getSharedPreferences(String name, int mode).
The getPreferences(int mode) method is a convenience method for the above and simply passes the Activity class name as the name parameter. This implies it should really only be used for a given Activity to store its own internal preferences and not preferences that need to be global to other app components.
In the case of a BroadcastReceiver the onReceive(...) method is passed a Context parameter so you can use context.getSharePreferences(<some_name>, <mode>) to get the SharedPreferences saved by the Activity.
public class AndroidWalkthroughApp4 extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public void onResume() {
// get EditText object
EditText editText = (EditText)this.findViewById(R.id.edit_text);
// get preferences object
SharedPreferences prefs = this.getPreferences(MODE_PRIVATE);
// set text to our saved value
editText.setText(String.valueOf(prefs.getInt("chars", 0)));
// don't forget to do this, or your app will crash!
super.onResume();
}
#Override
public void onPause() {
// get EditText object
EditText editText = (EditText)this.findViewById(R.id.edit_text);
// get preferences object
SharedPreferences prefs = this.getPreferences(MODE_PRIVATE);
// create editor from preferences object
SharedPreferences.Editor editor = prefs.edit();
// save and write length of EditText
editor.putInt("chars", editText.getText().length());
editor.commit();
// don't forget this either!
super.onPause();
}
}
So I have two activities: main with all data and secondary with Preferences. There are two arrays in main activity that I want to have access to from Preferences activity and work with this two arrays. In fact, I need to reset all data in arrays to default. Is there any way to do it?
I've tried to use SharedPreferences because I store all this data in it. I changed values in it from Preferences activity, but data in main activity haven't changed, I guess, because it's not being restarted, just paused.
You can use SharedPreferences and register a OnSharedPreferenceChangeListener and/or update the data in the onResume() method of your Activity.
Here's some basic example:
public class MainActivity extends Activity implements OnSharedPreferenceChangeListener {
private SharedPreferences prefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// get your SharedPreferences objects
prefs = ...;
}
// This method will be called every time your activty comes to the front
#Override
protected void onResume() {
super.onResume();
// register a listener to get notified when the preferences change
prefs.registerOnSharedPreferenceChangeListener(this);
// do whatever you need to do to update the data
updateData();
}
#Override
protected void onPause() {
super.onPause();
// unregister listener if another activity comes to the front to save battery
prefs.unregisterOnSharedPreferenceChangeListener(this);
}
// this method will be called when some preference changes
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
// do whatever you need to do to update the data
updateData();
}
}