sharedpreferences remains when the app is closed - android

I'm saving some data into sharedpreferences and my problem is the data remains even when the App is closed, and even if the pda is reset
Another question about the lifecycle, my App should keep working in background and it does if i press the "menĂº" button of my pda, choose other apps in the meanwhile, etc... But if I press the "back" button, it executes the ondestroy method and the App doesn't keep working.
Thanks!

sharedpreferences are designed to do just that. persist data between app executions..
-- http://developer.android.com/guide/topics/data/data-storage.html#pref
if you want your app to remain active in the background you need to have it run as a service.
-- https://developer.android.com/training/run-background-service/create-service.html

The sharedpreferences are intented to stay when the app is closed. It's just an xml-file storing your data. If you don't need some of the values you either may reset them in the onCreate of your Base-Activity or define a global class that extends Application and store your data there in global variables.

Related

How to restore data in Android?

I recently got into Android development and I'm a bit confused about how the savedInstanceState works. Let's say I was making a game and I want to save the player's score, would I be able to save it during onSavedInstanceState() to the savedInstanceState Bundle and always be able to retrieve the score from it no matter whether the device was shut off or the user just completely closed the app?
If your question is how much is Bundle object kept in mememory, that would be temporarily.
The data is held in memory until the application is alive or killed by the OS (lack of memory), in other words if you force close the app (shut down the device or close the app) onSaveInstanceState is not used.
However if you want to permanently store the data you would have to use SharedPreferences and SQLite database.
I'm not sure I fully understand you but let me answer you and then tell me if this what you mean
the savedInstanceState has nothing to do with the save game, the save game usually should be when a cretin event happens or sometimes you choose that
if the user closed the game by pressing the home button for example you will save the game automatically for him , you should do that by overriding one of the Activity methods, onPause() is your best bet, because you want to keep the save even if the user restarted his phone for example.
see this for activity life cycle:
http://developer.android.com/training/basics/activity-lifecycle/index.html
On the other hand, the savedInstanceState is a mechanism used by android to save the activity temporarily, if the user went back to the game directly before the activity completely gets killed by the OS, you can restore the state of the activity instead of loading the game from the beginning and going to the start menu.
this principle holds in general not just in game.
to summarize it: the savedInstanceState is a way to restore your activity form the memory before it gets killed rather than loading it again. and it's NOT a way to save data premenantlly on the device
if this is what you want, then you can ask about how to work with the savedInstanceState

User Logout upon terminating application in android

I am looking for a way to logout the user of my app automatically when the application has been terminated. I dont believe there is anyway to do this as only the activities have an onTerminate() function call. I am coming from an ios background where i an app, i could call a logout() function when the user entered the background. Is there a similar sort of parallel for android?
The reason i am looking for this option is because i have a global helper class that extends Application to store some user credentials and other info. If the application gets terminated by the os, this data is lost from what i have read. So i would like to force the user to log back in again to repopulate this data if it was destroyed.
Save user credentials to shared preference, Then when press logout button clear data in shared preference and finish the activities and cancel all background services related to your app

Persisting state in the android Application class

I am developing an Android application consisting of over 10 activities. I have some state objects that I access in almost every activity and for this purpose these were implemented as global static variables in the MyApplication class.
I noticed that this approach is OK as long as the user is "in" the application. However, when he presses the home button and opens another apps and then goes back to my app through the "Recent activities" button, I see that the Android system resets the statics from the MyApplication so I have to deal with NullPointerExceptions. I know that this behaviour is caused by Android killing and recreating the application process.
I know that the best way to persist this kind of data is using SharedPreferences or SQLite, and I have no problem checking if MyState==null in the onCreate for and restoring it, but the problem is that I don't know when to properly store my state object (in prefs or database). I tried to override MyApplication's finalize() - no good, I saw that onLowMemory may not be called, I don't see how can I use onPause, OnStop and so on because I have so many activities that the serialization de-serialization would considerably slow down the app.
Any thoughts?
Thanks in advance!
It is better to not depend on the Application class unless you need to load some data, before anything else is started. Android can kill your process at any time to free resources, so your app should be able to handle this. Save all of your data in a snigleton class, and load it lazily -- check for null, and if so load on first access. It the state needs to be persistent, consider staving it file/shared prefs. If not, your app can probably live without it, so just make sure you check for null, etc.
Generally, you should persist state when activities become inactive -- onStop(), onPause(), but you can save as soon as it makes sense (e.g., the user has entered all required data). Spin off an AsyncTask to save data in the background and let the user continue their work.

android save session state across activities

What is the best way to maintain session information across multiple activities?
The question What is the best practices on Android to keep data between activities deathes/restarts for the whole application session? has some ideas, but does not really help me.
*My application has multiple activities with the manifest tag singleTop. They essentially work as different tabs - they each maintain their own set of fragments and back stack and so putting it all into one activity would break navigation for the user.
I am currently saving the session data as a static singleton created by my Application subclass. This works fine most of the time, except when the entire application is killed by the OS to save memory (as mentioned in the above link), say, when the user gets a call on a device with low RAM.
The only notification the app has that it is going to be killed (as far as I know) is
Activity.onSaveInstanceState(Bundle outState)
So the problem is this: onSaveInstanceState will eventually be called on every activity, not just the top-most one (the one that will appear when the user eventually returns to my app). When each non-top activity resumes, I could use Activity.onRestoreInstanceState(Bundle savedInstanceState) to restore my singleton session, but non-top activities would have old copies of the data (they may have been navigated-away from long before the user got the call).
One solution would be to only restore data to the singleton session Only if it is currently empty, but this relies on the first activity to receive Activity.onRestoreInstanceState being the top activity. This is not always the case - if the user gets a call and then returns to the app via the launcher icon, then the Main activity will be resumed first and brought forward, not the activity the user was on when they got the call.
A simple notification in the Application class that the application is being killed by the OS (not the user) is really what I need - I would then save the session to a file, and read it back on the first call to Activity.onRestoreInstanceState, but AFAIK this doesn't exist.
If you have some data that you want to store when app closes and reload them when app starts, you can have a mechanism to store and retrieve them on application's shutdown and startup. To do this override onStop() and onStart() methods on Activity's lifecycle.
And I think the best way to store and retrieve data in these two methods is SharedPreferences.
I would simply insist to use Application class to save the session. Using Application class you will be able to access the session everywhere were you are having Context so probably you can access in your whole Application. Application class also maintains the value after you Application is closed so its better to clear previous session when your Application is re-launched.
As the main use of Application class is to maintain global state of variables so that they can be used throughout the Application with updated values.

Android: change variables (counters) of a closed application using a service

stackoverflow community.
I have a problem that I've been trying to solve since a few days ago.
I have a service running in an Android application that receives and sends messages. For those messages, I have counters that save the ammount of sent and received sms and errors. For example, when a message is sent, the counter adds +1 and shows the total on screen (in a not focusable editview).
Another thing I do is bind my service, so I can switch it on or off according to my needs. Everything works fine when the application is running, but if it is finished my variables are lost, but I need to keep counting the messages somehow and show the values when the user opens the application again. How can I do this?
I've been using shared preferences variables to save these numbers and others configurations, but when the app is killed, those numbers can't keep increasing.
When the application is closed, can I save the counters values somewhere? Can I access to the shared preferences from the service with the application closed? What if I use a content provider? Can I access to it from the running service even if the app is closed?
Regards.
There is no problem accessing shared preferences from a service. So, just save your variables on your services onDestroy() method and reload them onCreate();
This should work to get the preferences:
Context ctx = getApplicationContext();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
Here's a great answer: How do I get the SharedPreferences from a PreferenceActivity in Android?

Categories

Resources