AndroidStudio - Save EditText when activity change - android

Ok so, there's a list of editText that the user fill with all names of players, say it's activity 2. And then click on start and play the game on activity 3. When he comes back to activity 2, the names are still in the editTexts and he can just add a participant if he wants and that's okay, but when he backs off in the menu, activity 1, and then open the activity 2 again, all the names are erased.
Is there a way to save the editText content in their places even when he leaves the activity 2 and comes back in it after? How can you achieve that?
Can you avoid calling the destroy method when back is pressed or do you need to save them somehow and put them back in?
Thanks!

If you want the names only during the application is alive, you can store the names in a Singleton class.
Or if you want the names even if the application is killed and opened again, you have to store it in a persistent storage. Either SharedPreferences or a Database (SQLite).
Check out the docs:
https://developer.android.com/training/basics/data-storage/shared-preferences.html
https://developer.android.com/training/basics/data-storage/databases.html

According to Save data in activity's onDestroy method You should save your data in the activity's (activity 2 in your case) onStop method. Technically speaking, you could then save that wherever you wanted and pass it back to activity 2 in the onStartActivity intent.

Related

Save state for particular duration- android

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."

onBackPressed - avoid destroying activity

I have two activities - activity A starts activity B. Then activity B loads some stuff from database, and visualizes the data. It takes some time (5-10sec) to fully initialize all the stuff in B.
My problem is that if I press back button in B, it destroys B activity (calls onDestroy) and returns to activity A. I still want to return to activity A, but without destroying B, because if I launch B again, I have to wait again before it does all the stuff (which is annoying). Is this possible somehow?
Thanks for your help!
You can use Fragments, but what you really want to do is cache the information. Otherwise you'll reload on device rotation anyways (unless you use Fragments and setRetainInstance to true, but this can cause other headaches).
I would use a CursorLoader on Activity B's onCreate. onLoadFinished you cache the result and setup your UI. On subsequent loads the results are cached and you forego the loader. What's more, using the CursorLoader will alert you if the underlying database results change.
I think you do not see the problem from the right point of view.
I'd say that you can't prevent B to be destroyed if Android wants to (because it's up to it to handle the activities).
However, you have the choice to move all the long initialisation in a third class which can be persisted all the time. So you should make this init phase independant from your B activity.
I think that putting all this in an attribute of your Application class would be a good idea.
Maybe you can use AndroidFragments
Use SharedPreferences to store key-value pairs then use getSharedPreferences() to retrieve them.
When you press back button Activity b is destroyed. It is how android works. I would not try to override the default functionality
Once you get data from data base you can cache then some where and load it.
http://developer.android.com/guide/topics/data/data-storage.html. Check the topic under Saving cache files.

Application crash, restoring state

I've got a parent Activity from which all others are derived. In my first-screen activity(android.intent.category.LAUNCHER) I call methods from parent Activity which populate ram-sqlite dictionaries and it's the only place where it happens.
I'd like to investigate the following scenario: application crashes, those in-memory dictionaries get erased. Is it possible that on the next launch user will be placed on some activity different from "main" ? In that case dictionaries will remain empty and I'll get another crash. Is it possible ? What should I do to prevent it - create Application derived class and if-check, populate dictionaries there ?
Thanks.
If the application crashes you wont be starting the same (crashed) activity again. But if some data are very important for the state of your main activity at launch, then you should be sure to save them persistently as they change. So you shouldn't only save your state in your activities onStop() methode.

Android - opening series of activities after restart

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!

does object die navigating between activities?

I have an application that navigates to the same activity but each time the activity loads with different parameters. In my application it's a parsed data content retrieved from url. First thing I want to ask: When I push the backbutton of my device I get my earlier activity without being recreated. Is the objects in this activities alive and can I reference them?
Second question is if my first question doesn't make sense, what do you advice me to do?
If you look at the Activity life cycle, you'll notice that as long as your phone has enough memory, your first activity is kept in memory, and with it any member with the data it contains.
But if your phone needs to have some memory, it can kill any activity kept in background (any activity but the one being shown to the user), which means that you'll loose any data that was in your first activity.
To know which happened, keep in mind that the onResume() method will always be called when your activity is brought to foreground (either on creation, or when you navigate back to it), but onCreate() will be called only when your application is created from scratch (meaning you don't have any saved data).
You should use the bundle mechanism to save data when your activity is paused, and load it when you come back to it. Read the paragraph about Saving Activity state in Android doc to see how to use this.
You are not guaranteed that in memory data will be around once you leave an Activity. Read through this part of the dev guide thoroughly to understand the lifecycle of an Activity: http://developer.android.com/guide/topics/fundamentals/activities.html
If you need to persist information, you should override the onPause, onStop, and/or onDestroy methods of your Activity. You can then save your state using SharedPreferences, the SQLite database, or even a flat file.
In the manifest file add the following to the activity:
android:launchMode="singleTop"
In your example what is happening is when you navigate back to the activity using the back button you are bringing up the activity from the stack. When you navigate to the activity inside of the app what is happening is a NEW activity is being created, while the original is still on the stack. The singleTop launch mode will pop the activity out of the stack if it is there when you navigate to it in the app, and only create a new activity if it is not on the stack.
Without singleTop each time you launch the activity in the app it will create a new instance and you will find there are times you have to hit the back button on the same activity more than once due to multiple instances.

Categories

Resources