Retaining the data in the view during activity switch? - java

In my android app the user can enter the text in the EditView and the click on a button which takes him to an other activity where he can select a contact ... and then press a button which
brings him back to the first activity...
now the problem is I need to pass the selected contact to the first activity and display it (which i have done it using a bundle) but i am unable to retain already entered text in the EditView... which i should do (but the text should be retained with out passing it through the the bundle and getting it back)
thanks :)

The text in a view component is automagically saved by the OS, even after a soft kill (user changed phone orientation), but not after a hard kill, the user hit the back button while the parent activity was in focus. So, unless you are doing something non-standard, such as calling onSaveInstanceState without calling super.onSaveInstanceState, the data in the view state should persist.
One solution would be to save the text in the view component as a non view instance property before you launch the child activity, and just read this value back when the focus returns to the parent activity in the method onActivityResult.
JAL
EDIT: The Android Docs Activity page has been extensively updated. View state will not be saved if the widget does not have an ID.
EDIT: What I am saying is that the view state should be persisted by the OS. You should not need to save the view state manually. On a hard kill, you would need to save the state of your activity IF that is the expected behavior of the activity. So here is some code that saves the activity state. Given an instance variable:
String password;
Here we save state on a soft kill:
protected void onSaveInstanceState(Bundle outState){
password= editTextPassword.getText().toString();
outState.putString("password", password);
super.onSaveInstanceState(outState); // save view state
}
Here we save state on a hard kill
#Override
protected void onStop(){
super.onStop();
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("password",password);
editor.commit();
Here we restore state in onCreate(Bundle savedInstanceState):
if( savedInstanceState!= null){ // get saved state from soft kill after first pass
try {
password= savedInstanceState.getString("password");
Log.d(TAG,"RestoredState!");
}
catch(Exception e){
Log.d(TAG,"FailedToRestoreState",e);
}
}
else { // get saved state from preferences on first pass
SharedPreferences prefs = getPreferences(MODE_PRIVATE); // singleton
if (prefs != null){
this.password= prefs.getString("password","");
Log.d(TAG,"gettingPrefs");
}
}
Log.d(TAG,"onCreate");
Also given the fact that IF onSaveInstanceState is called it will be called before onStop, it is possible to use the flags isSavedInstanceState and isSavedPreferences to write to prefs ONLY on a hard kill if you reset the flags in onResume as:
protected void onResume() {
super.onResume();
Log.d(TAG,"onResume");
isSavedInstanceState= false;
isSavedPrefs= false;
}
Setting the flags in onCreate will not result in the desired outcome.

Related

Resuming activity from where it left if user killed the app manually

I am working on one application in which i move from Activity A(Main Activity) to Activity B to Activity C.
All of this is working fine but the problem occurs when user killed the app by removing it from Task tray.
To understand my problem say user moved from A to B and then C but before finishing the task in activity C user killed the app.
so when user again opens the app by pressing App icon i want to start the last activity C where user was when he killed the app instead of android default behavior of starting(Main Activity A) a fresh instance of app again.
What i have tried:
1) I tried using "onSaveInstanceState" and "onRestoreInstanceState", but i think they are used when orientation is changed or we go back by pressing back button.
2) I tried to save everything in "onPause" as onpause calls 99.99% times when activity destroyed and by using static flags i opens the last activity and it worked for me but i want some good example or technique to this work.
so can anyone help me on achieving the same..??
I request fellow members to provide code examples.
thanks in advance.
Store the state in every Activity's #onPause().
So in every Activity you want:
#Override
protected void onPause() {
super.onPause();
SharedPreferences prefs = getSharedPreferences("RESTART", MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putString("last_left", getClass().getName());
editor.commit();
}
And a Shell Activity which will be a Launcher, Main Activity:
public class Shell extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Class<?> classActivity;
try {
SharedPreferences prefs = getSharedPreferences("RESTART", MODE_PRIVATE);
classActivity = Class.forName(prefs.getString("last_left", getClass.getName()));
}
catch(ClassNotFoundException ex) {
classActivity = your_Activity1.class;
}
startActivity(new Intent(this, classActivity));
}
}
[Source Modified]
you can use SharedPreferences to store last user state.#onPause activity
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("state", "A/B/C");
editor.commit();
OnResume Activity
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String stateApp = prefs.getString("state", null);
if (stateApp != null) {
switc(stateApp){
case 'A':
// Go TO A activity
break;
case 'B':
// Go TO B activity
break;
default:
// Go TO C activity
break;
}
}
The Intent that was used to launch the activity is saved by the system when the process is about to be killed.Once the user returns into the app which has been killed, then the app is restored and the same Intent (Activity A in your case) is fired to launch the activity including all the extras that it might have.
Go for SharedPrefrences:https://developer.android.com/reference/android/content/SharedPreferences.html
refer the official documentation.
Try to use sharedPreferences concept, save the activity name in sharedPreferences while the opening of that activity, then check the sharedPreferences value while reopening the application. I think you got it!
sample tutorial link:
https://developer.android.com/training/basics/data-storage/shared-preferences.html

How to populate the EditText data while on resuming the state?

Here is the following scenario:
Filling the EditText and other Fields in Activity A
Moving from Activity A to Activity B on Buttonclick
Now Moving from Activity B to Activity A on Button Click
populated EditText is gone now. They are all empty
These fields should be pre-populated (as user has already filled them)
Is there any way to save the current state of Activity A. So that I can populated the EditText back? If not then How can I achieve the above task?
Use SharedPreferences.Editor to save the EditText data onPause, and retrieve the data with SharedPreferences onResume. That's the easiest way.
How are you moving from b back to a? If youre using an intent then your starting a new instance of that 'a' activity. Like some one mentioned above you should be using finish in your b activity which would take you back to a. If you need to populate a with data from b then you should use startActivityForResult - http://developer.android.com/training/basics/intents/result.html
To save the activity state, override OnSaveInstanceState() method.
#Override
protected void onSaveInstanceState(Bundle savedInstanceState)
{
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("key", somevalue); //save your data in key-value pair
}
and restore the value using,
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
somevalue = savedInstanceState.getString("key");
}
Use this method if you are destroying the activity and creating it again.

How can i have my Android app resume where i left off

I have simple counter application where, whenever you click the button, a textview shows the number increasing. If you click the button 10 times, the textview shows 10. Then, when I exit from the app and launch the app again, the application restarts all the activities I have done previously.
How can I continue to count where I left off previously? For example, I want to open my app and count up to 8 with the counter. When I exit, and after re-launching the activity, I want to continue counting where I left off from 8.
Please take a look at the source code:
TextView tv4;
ImageButton button5;
int counter=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_ikinci);
tv4=(TextView)findViewById(R.id.textView4);
button5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter++;
tv4.setText("" + counter);
}
});
On your activity's onStop() method try to save your data in SharedPreferences
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putInt("key", count);
editor.commit();
And when you launch it, on your main Activity onCreate() method retrieve your SharedPreferences value by key and continue where you left off
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
int count = prefs.getInt("key",0); //0 is the default value.
If you need to store little pieces of data throughout your activity's lifecycle it should be enough to store your counter variable in a Bundle inside onSaveInstanceState (Bundle outState) method. Note - don't forget to call super of that method after putting your variable into the Bundle.
This particular Bundle is passed to two methods on recreating Activity: onRestoreInstanceState() and onCreate() methods. So you can reset you instance variable from there.
For more info look here: http://developer.android.com/training/basics/activity-lifecycle/recreating.html

How to recover data after closing another application

I'm developing an Android application and I need to open pdf files and return to same activity when back button is pressed.
Problem
I correctly open pdf file (from ActivityOne) using an intent and starting activity, but when I press back button, all data that I had in the ActivityOne (and previous activities) have been lost.
Here is my code of starting activity for showing pdf:
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
+"/"+ myApplication.getUsuarioActual().getFacturaActual().getPdf());
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.fromFile(file));
intent.setType("application/pdf");
startActivity(intent);
What do I have to do to solve that? Same occurs when I open another application and close it: when return to my app, it shows an error saying that all data is null.
EDIT
After reading that question, as #TheCharliemops recommended me, I know it is what I need, but I have another question related to that.
I have a class myApplicationthat extends Application to maintain global application state where I save all data that I read/write in different Activities.
My question is if I have to save all data I have in myApplication in every activity using onSaveInstanceState or there is some easiest manner to do it.
Firts of all, welcome to SO!!
Here, #reto-meier explains how to save the activity state in Android. I think that could fix your problem. I put his code here for future people with similar problem.
He says that you must override onSaveInstanceState(Bundle savedInstanceState) and onRestoreInstanceState(Bundle savedInstanceState) as following code shows:
Reto Meier said:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putBoolean("MyBoolean", true);
savedInstanceState.putDouble("myDouble", 1.9);
savedInstanceState.putInt("MyInt", 1);
savedInstanceState.putString("MyString", "Welcome back to Android");
// etc.
}
The Bundle is essentially a way of storing a NVP ("Name-Value Pair") map, and it will get passed in to onCreate and also onRestoreInstanceState where you'd extract the values like this:
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
double myDouble = savedInstanceState.getDouble("myDouble");
int myInt = savedInstanceState.getInt("MyInt");
String myString = savedInstanceState.getString("MyString");
}
I hope this helps you.
Regards!

Reload SharedPreferences on resume? (or how to refresh/reload activity)

How can I reload SharedPreferences when I resume from one activity to another? If I resume, it is possible that user has changed the settings. Is it possible to reload SharedPreferences or do I need to refresh/reload activity. And if, then how?
There is no difference in how you get and set SharedPreferences normally and from doing so in onResume. What you will need to do in addition to getting the most recent preferences, is update any objects you have in the Activity that use preference values. This will ensure your Activity is working with the most recent values.
A simple example:
protected void onResume() {
super.onResume();
getPrefs();
//...Now update your objects with preference values
}
private void getPrefs() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String myPref = prefs.getString("myPref", "");
}

Categories