I have an android requirement where i have created a form like structure have radio buttons, edit texts and so on. When the user make half entries to the form and say moves away from the page either by back button or battery off. When he returns to the form, the same state of half filled form should re appear. Please suggest if android has internal functionality to save the form state and restore when the user revisits. Also, the stored contents should be saved only for particular duration say one hour after which the fresh form should appear. Please help with possible methods applicable for me to start with.
I recommend reading the Android Activity lifecycle. From the webpage:
"In addition, the method onSaveInstanceState(Bundle) is called before placing the activity in such a background state, allowing you to save away any dynamic instance state in your activity into the given Bundle, to be later received in onCreate(Bundle) if the activity needs to be re-created. See the Process Lifecycle section for more information on how the lifecycle of a process is tied to the activities it is hosting. 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."
Related
I have an app in which I programmatically create an EditText view. I assign an ID to that view using setId()
myEditText.setId(100);
so that Android automatically saves that object's state when pausing/stopping the app (as I was advised to do here). It works in these cases:
(1) When I leave the app using the "Home" button: if I then come back to the app, the object's state (displayed text) is restored, as expected.
(2) On a screen orientation change (which involves Android automatically destroying the activity and restoring it through a Bundle). The object state is also kept.
However, it doesn't work in this case:
(3) When I leave the app using the "Back" button: if I then come back to the app, the EditText object is empty.
Any explanation as to why this happens? Does Android really distinguish between leaving the app with "Home" and with "Back"? According to the documentation, the object's state should be automatically preserved, through a Bundle, even when the activity is destroyed. And that clearly happens in case (2). But not in case (3)!
If this is normal behaviour, how could I have the app's state automatically saved and restored when the user presses "Back"? I know I could use the SharedPreferences for that, but I'd rather have Android do that automatically, just as it does in cases (1) and (2).
This happens at least in Android 4.0 and 4.2 (I haven't tested others).
You really should study activity life cycles as there are many many ways to solve the problem. Since your activity is typically pulled off of the stack and destroyed when you navigate back one quick but not necessarily the best way is to make sure your activity flagged as singleTop or singleInstance in the manifest that way it is not pulled off of the stack and recreated when you navigate back and forth. You could also use the singleton Application class. Or pass the text back and forth as params. Or use a database. Or use MVC or some other programming paradigm that will allow your views to be destroyed and recreated with out the data populating them going with it. Lots of "or's". Study activity life cycles and then look at how you have your application architecture setup already and choose the method that will work best for you.
http://developer.android.com/training/basics/activity-lifecycle/index.html
http://developer.android.com/guide/components/tasks-and-back-stack.html
I think I found the explanation. I only needed to read the doc more carefully (thanks to #lentz for one of the links); see here and here:
When your activity is destroyed because the user presses Back or the activity finishes itself, the system's concept of that Activity instance is gone forever because the behavior indicates the activity is no longer needed.
If the user presses the Back button, the current activity is popped from the stack and destroyed. The previous activity in the stack is resumed. When an activity is destroyed, the system does not retain the activity's state.
The above explains behaviour (3) in my question.
However, if the system destroys the activity due to system constraints (rather than normal app behavior), then although the actual Activity instance is gone, the system remembers that it existed such that if the user navigates back to it, the system creates a new instance of the activity using a set of saved data that describes the state of the activity when it was destroyed. The saved data that the system uses to restore the previous state is called the "instance state" and is a collection of key-value pairs stored in a Bundle object.
The above probably explains behaviour (1) and (2).
What I don't see is why the user pressing Back should be interpreted as "the activity is no longer needed" ("its state needs not be preserved"). But that's a different matter.
I have a MainActivity and a second Activity which has an EditText. I want that the content of EditText always gets saved. However I don't want a EditTextChangedListener which writes a file after 1 char has changed.
What is a good solution? I thought about onPause or onBackPressed.
What about the home button? I think the app remains open, so is there any need to save? And what about other interrupts like phone calls? Does onPause catch all that?
Thank you.
Yes onPause gets called whenever your app gets interrupted or goes to background check Activity life cycle
A good solution is to include such logic in the onPause() method. It will always be called in all situations. This is what the developer documentation says:
you should use the onPause() method to write any persistent data (such as user edits) to storage.
One thing you should keep in mind is that this method may be called more frequently than desired, for example, when your screen light goes off (some ppl have 15sec screen light timeouts). So, you should not put in too many expensive operations inside there.
As for pressing of home button, it is recommended that you save the data (at onPause()). The reason is that your activity is in the background but it may get destroyed. The system may destroy the activity if it needs to reclaim the memory. (For example you start too any other apps afterwards and put them all in the background) From the documentation:
Stopped: The activity is completely obscured by another activity (the
activity is now in the "background"). A stopped activity is also still
alive (the Activity object is retained in memory, it maintains all
state and member information, but is not attached to the window
manager). However, it is no longer visible to the user and it can be
killed by the system when memory is needed elsewhere.
No. The correct answer here is to listen for the "return" key event. That signifies that the user has completed input to the field, and trigger the save of the field contents to the file. It's useful in many other circumstances too.
See this answer: Android Use Done button on Keyboard to click button
Peter.
At the moment I'm a little bit confused about the lifecycle management in Android. There are at least 4 possibilities to resume retained data after an Activity comes back to the foreground:
Android handling: If there is enough memory, Android stores and resumes the important data (checked radio buttons, text of EditText,-... and so on) after Activity restart, the user has the same state as before as the Activity went into background.
onPause, onResume: Overriding onPause and save the important data to a database or text file and resume it when onResume is executed next time.
onSavedInstance(Bundle), onRestoreInstance(Bundle): I can save the data as key-value-pair into bundles and restore them after onRestoreInstance is executed.
onRetainNonConfigurationInstance(), getLastNonConfigurationInstance(): I handle all my storage issues in one big object and read getLastNonConfigurationInstance() out when onCreate is executed.
Although it is confusing which approach is best, I guess it relies on development experience to know when to use which possibility. If you have some good examples for each I would be glad, but this is not my question. I wonder how to deal with all that when I have different Activities and one Activity will be killed by Android when it pauses in background:
In my case I have a MainActivity and a MessageActivity. The MessageActivity consists of a ViewSwitcher which consists of two states. State one is a radio button choice list. State two is an EditText with two buttons (send and abort). When I monkey test each state, hit the Android home button, and restart the application, the right Activity with the right state and the old data comes into foreground, when I leave the handling to Android. So that works.
But what happens when Android destroys the MessageActivity in background:
If I use the Android way, the data is lost and I guess MainActivity (instead of MessageActivity->state(1 or 2)) will start next time after I relaunch the application (is that correct?). So when I'd like to keep the data of MessageActivity, I have to use one of the other three possibilities.
How to do that neatly, when the application entry point (so the MainActivity) differs from the last active Activity. The problem is that I have to resume a special Activity with a special state of ViewSwitcher. I could start MessageActivity out of MainActivity with startActivity(Intent) in onStart() or onResume() method (because MainActivity is probably the entry point) but then I run into a lot of logical problems in Lifecycle management. Due to this fact I don't think that this is the right way to do that.
But, what's the right and best way to do that?
I guess MainActivity (instead of MessageActivity->state(1 or 2)) will start next time after I relaunch the application (is that correct?)
No, I don't believe this is correct, depending on what your code does in onCreate(). It certainly doesn't need to be correct if you go about things the right way. A simple way to test this is to rotate your screen, which recreates the running activities, unless you have overridden the default configuration change behaviour.
I recommend reading this section in the android docs carefully:
http://developer.android.com/guide/topics/fundamentals/activities.html#SavingActivityState
In particular:
even if you do nothing and do not implement onSaveInstanceState(), some of the activity state is restored by the Activity class's default implementation of onSaveInstanceState(). Specifically, the default implementation calls onSaveInstanceState() for every View in the layout, which allows each view to provide information about itself that should be saved. Almost every widget in the Android framework implements this method as appropriate, such that any visible changes to the UI are automatically saved and restored when your activity is recreated. For example, the EditText widget saves any text entered by the user and the CheckBox widget saves whether it's checked or not. The only work required by you is to provide a unique ID (with the android:id attribute) for each widget you want to save its state. If a widget does not have an ID, then it cannot save its state.
What this means is, that so long as you don't force any UI state in any onCreate() calls, your activity stack and UI state will be restored.
Personally, my preferred approach is to keep as little state as possible in member variables of my activities, saving and restoring it with onSave/RestoreInstanceState(), and relying on the default implementations to save the rest of the UI state (text box contents, etc). Data that should persist between sessions I commit straight to my DB or preferences as soon as it's changed (e.g. in the on-click handler). This means I don't need to worry about the activity lifecycle for that. As much as possible, my UI just presents a view of the data in my DB (using CursorAdapter etc.).
Edit:
Regarding restoration of the whole activity stack:
When the user leaves a task by pressing the HOME key, ... The system retains the state of every activity in the task. If the user later resumes the task by selecting the launcher icon that began the task, the task comes to the foreground and resumes the activity at the top of the stack.
(See http://developer.android.com/guide/topics/fundamentals/tasks-and-back-stack.html)
It's not my attempt for a best answer, but it's too long to get in the comments section.
First I will suggest not to rely on the "Android way" - this will result in inconsistent application behavior depending on the free memory of the device - bad practice.
My suggestion is to save your state-dependent data in key-value pairs in SharedPreferences, every time you go into onPause() in your MessageActivity. Store a flag in SharedPreferences, which indicates which was the Activity that was last opened (if you only have two Activities you can easily go 0/1 or true/false flags).
When you re-launch your application, it's normal to start the Activity marked in your AndroidManifest.xml as "entry point". So naturally you'll check the flag in onResume() in your MainActivity and start the other Activity if needed. In MessageActivity's onResume() check the values in SharedPreferences and fill in what's necessary...
If your application is "resumed" to the last Activity in the ActivityStack this will call onResume() in the last Activity in the ActivityStack.
The way I have handled an issue like this in the past, is to have a service running in the background, which handles the flow of information from different activities via either Intents and listeners (preferable, since they are the most easily decoupled solution), or if you are extremely careful, and the only viable solution for some reason is to store the data through direct property access or method calls, you can use static properties/methods on the service class as well. However, I would strongly recommend using the Intent/listener method as it is generally more flexible, thread safe, and decoupled. Additionally, it is wise to make sure that not much is happening at any point in time (in other words, only use this service for Intent handling) when it's not needed, otherwise the Service will tend to hog CPU time as well as RAM, when it's not really needed.
Some resources to look at when it comes to this approach would be IntentService and its related classes, including the superclass, Service. IntentService, however, it is worth noting handles a few more things about async Intent processing, etc that Service does not automatically come with.Hope this helps you!
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name=username.getText().toString();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = settings.edit();
editor.putString("username", name);
if(name.equals("xxx")) {
Intent intent=new Intent(currentactivity.this,nextactivity.class);
intent.putExtras(bundle);
startActivityForResult(intent,0);
}
}
});
there is my situation. I have same activities which goes one by another, no matter what they are doing. Lets name them from the start of alphabet. When users uses my application, he goes through activities and makes his own path between them, so he could with back button go back in respecitve back order.
He starts with act. A - D - F and with back button he goes back as from F to D and A. Ok. Now, when Android system resolves the application is no longer in use or needs lot of RAM in some particular time, system kills it. My goal is to find, how to restore application to its former state including order of opened activities?
It might not be clear, so here is the example:
User has open activities A (login) - D - F - G, minimize it, after some time, app is killed. When he start this application again, he needs to login at activity A and than he has to see activity G (= he was there last time), and when he push back button, he will go do activity F, then activity D and so on... Is like revieving an row of activites. I know I have to persist all the information stored in my activities (D, F, G), but is it acutally possible to persist app state like that?
Thanks for any comment on this
Solution:
I am tracking flag, which identifies the state my application is in. If it is s 0, it means I am opening new activity normally. On start of each activity I put into shared preferences string, which contains all my activity history. Each activity has it's own id (again sharedPref). In another shared pref I am saving as a String formular data (or data with GUI), when onPause occurs. I set flag as a 1. When app starts and flag is 1, I revive application stack from sharedPref. Set data for each of them from another Shared Pref. And that's it, application state is revived :-)
You can persist anything you need to, it just a matter of how and what is going to be beneficial. There are multiple techniques that have been used to persist state over the years. Nearly all of them are available to you, but will require careful management on your part. Depending on what your application does, there may be special tricks available to you, as well.
Step 1
Determine what each Activity needs in order to run effectively. Determine what you can recalculate and what you absolutely should not recalculate. For instance, if one of your Activities is a Cursor Adapter of some kind and works according to a key to a table, you don't need to persist the entire Activity, you simply need to hold onto whichever _id relates to that particular Activity run.
Step 2
Since you are wanting to track Activity history, you will need some representation of that history. What you are proposing is a stack model, so you will want to write your own stack object and find an easy way to identify each activity in that stack. Do not try and save the actual Activity references as this will invariably lead to leaks. You can then save this stack to a database, shared preferences, file or even parcel it to a bundle. Integer constants that identify each Activity might be one way to accomplish this.
Step 3
Decide on your method of save, and build the appropriate save and load methods for your stack and each Activity.
Step 4
Override the Back button to retrieve the top Activity identifier and its appropriate data on the stack. (As a note: your stack might be better placed in an extended Application) Then start the next Activity with its required data.
Step 5
When your "login" Activity (or Application) starts, load the stack. When authentication completes, reload the top Activity on the stack, passing its required data through Intent Extras. You don't have to open ALL of the Activities at once, just the ones that the user is on.
Step 6
In your onCreate or onWindowAttached for each Activity, have it add itself to the stack. In your onDestroy for each Activity, have it remove itself from the stack. Since you are persisting your data, you can easily finish() to indicate that the Activity is complete.
Step 7
In your onPause for each Activity have it save the state that you feel is important. You can even save the scroll position and just have it rescroll when the Activity restarts. In your onCreate have it regain its state via the extras that you supplied.
It is really as simple as all of that. If you need some samples, I can gladly provide.
FuzzicalLogic
Assuming all you need to do is reconstruct the path of activities from A to Z (or whatever), you don't need to make things too complicated. if you want to do it the right way, do the suggestion by Fuzzical Logic. if you want to get it running quickly and complicate things after that, you can start with this simple method.
Basically, you map each activity to a code, and maintain a simple text file. Each time an activity is invoked, it should append it's code to the text file. So you're really just writing to a file exactly what you explained in your question. In your example, you'd have "ADFG" in a text file.
When you exit an activity and go back, just read the file, chop off the last letter, and write it out. In your example, if you had "ADFG", pressed back, the file would now contain "ADF".
When your app starts, simply read the file and for each character, create the associated activity as you would normally. Read the file once and pass the string to each activity as it is created. So the root activity would read "A" and start that activity (passing the string "DFG" in the bundle), then that activity would read the next character and start the D activity (passing "FG"), and so on until the last activity sees that there's no characters left in the string.
Once that's all working, you can worry about how to store state information for each activity. Fuzzy's solution is by far the most elegant, but elegant and ASAP don't usually mix, so it's your call. I'd separate the stack data from the state data for each item in the stack. It's just easier that way IMO.
Hope that helps!
I am confused about activity lifecycle usage in the notepad example,notepad example use "edit in place" user model,inserting new record in onCreate method,
saving persistent state in onPause method,and save away the original text in onSaveInstanceState method.
I am a J2EE programer,I can not understand the logic described above. why not make things simple as following:
1.Not inserting new record in onCreate method.
2.When user pressing BACK,it is equal as pressing save button in the editorform,so execute inserting or updating in onPause method if activity.isFinishing() is true.
don't persiste use data if activity.isFinishing() is not true.
3.Not save the original text in onSaveInstanceState method,It is no necessary.If the activity is killed and back,restore user inputing data in the editorForm is adequately.
I think this logic is more traditional and natural.
Maybe I not understand the essence of the activity lifecycle.Please air your's opinion.
Thanks
L.J.W
the lifecycle of an adroid app under various conditions (e.g. switching screens, freezing, stopping etc.) is described in an excellent video tutorial by google. You may also want to refer to the slides of that talk, in particular, slide 16ff may be of great interest for you.
In any case you are right in thinking that understanding the lifecycle of an android app is the key to coding for android.