Save values before close the app? - android

I want to save some values before i closed the app. But i don't know if i must create a new file(.txt) and save it in; or i just can change strings.xml file and when i open app next time the saved values will be the right saved values or will be walues which i define them before first using. I know that exist really easy way to read from strings.xml file and so i think that there must be a way to set values in this file before closing (but i can't find on the net). Thanks for any examples or yours advice and explanation.

Android provides the SharedPreferences class to help you save simple application data.
You can use SharedPreferences class to save the config information or anything you want.
When you put the application in background or close it, onStop() will be called. You can override it to implement what you want.
Usage of SharedPreferences class is very simple:
step 1: Writing with SharedPreferences object
//Create a object SharedPreferences from getSharedPreferences("name_file",MODE_PRIVATE) of Context
private SharedPreferences pref;
pref = getSharedPreferences("info", MODE_PRIVATE);
//Using putXXX - with XXX is type data you want to write like: putString, putInt... from Editor object
Editor editor = pref.edit();
editor.putString("key5","value5");
//finally, when you are done saving the values, call the commit() method.
editor.commit()
step2: Reading with SharedPreferences object
//get SharedPreferences from getSharedPreferences("name_file", MODE_PRIVATE)
SharedPreferences shared = getSharedPreferences("info",MODE_PRIVATE)
//Using getXXX- with XX is type date you wrote to file "name_file"
String string_temp = shared.getString("key5");
The MODE_PRIVATE constant indicates that the shared preference file can only be opened by the application that created it.
The shared preferences file is save as an XML file in /data/data/<package_name>/shared_prefs folder

Do your save operation in your activity's overridden onStop() method.
As for where/how to save: follow the example here :
http://developer.android.com/guide/topics/data/data-storage.html#pref

You can do it using preferences. Check this tutorial and example
http://www.vogella.com/articles/Android/article.html#preferences
If data has to be shared between multiple activities then use Shared Preferences

Better go with shared preference for saving data but if you think you have save more amount of data then better go with database or save it as file.
Refer this LINK

Related

How to make android app data, app-wide available?

How can I make data available through my whole android app?
For instance, I want to display a user picture in the toolbar in every screen. Also, the name of the user is displayed in the navigation drawer in every screen.
Is a singleton the right approach for this? Or are other techniques better?
I have been googling a lot, but i can't find a good approach for my use case so far.
To use shared preferences:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
to save in shared preferences:
editor.putString("tag", "save me please");
editor.apply();
to retrieve from shared preferences:
String s = preferences.getString("tag", "default_value");
Notes:
You can make your tags as string constants to make sure you are always using the same value.
If you use the editor for multiple values, always remember to add editor.apply() in the end, to actually apply your changes.
If you want the editor to write the changes synchronously, use editor.commit() instead. You can save any type of variable in the shared preferences, just use the appropriate method (instead of putString use putInt, putLong, etc - same with the getSring). More on Shared Preferences in the API here

Is it possible to save a variable value in Android (in memory), even after closing the application? If so, how?

How is it possible to save a variable value in an Android app? Can the value be saved in memory? I am planning to save a float value in my application, so the next time the app is opened, the previous value will be loaded. How do I go about this? Shared Preferences or something else?
Yes. SharedPreferences is the best available option.
To store float value:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putFloat("storedFloat", storedFloatPreference); // value to store
editor.commit();
Also check this: http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#putFloat(java.lang.String,%20float)
Check this SO question. It nicely answers your question: How do I get the SharedPreferences from a PreferenceActivity in Android?
Yes its possible use shared preferences.
http://developer.android.com/reference/android/content/SharedPreferences.html
http://developer.android.com/guide/topics/data/data-storage.html#pref
You can also use sqlite data base to store the data and retrieve when you need it.
Your other storage options. you could store your values to a file in memory.
http://developer.android.com/guide/topics/data/data-storage.html
Look at the Storage Options Docs to be sure you pick the most appropriate type for you but if its just one value then SharedPreferences should work fine for you.
See The Docs for a good example on how to use SharedPreferences

can someone explain me how SharedPreferences works in Android in a very detailed yet easy understanding?

I'm novice in Android development and now I'd really like to learn Shared Preferences. I've googled it so many times and I don't think I quite mastered it.
I believe this Shared Preferences will help me to store username and a password on my login screen activity. Thanks you!
I made some videos about this as an audition for a job. They helped me get the job, and they're still available on Vimeo, so hopefully they can help you out.
Part 1: Saving Data
Part 2: Retrieving Data
Also, for what it's worth, be careful storing usernames and passwords in SharedPreferences. You can do it there, but read up on the risks in this other SO question: What is the most appropriate way to store user settings in Android application
For android, there are primarly three basic ways of persisting data:
shared preferences to save small chunks of data
tradition file systems
a relational database management system through the support of SQLite databases
SharedPreferences object help you save simple application data as a name/value pairs - you specify a name for the data you want to save, and then both it and its value will be saved automatically to an XML file for you. To save a data in sharedPreferences file:
Obtain an instance of sharedPreferences file:
SharedPreferences appPrefs = getSharedPreferences( or fileName, MODE_PRIVATE);
Create SharedPreferences.Editor object
To put for example a String value into SharedPreferences object use putString() method.
To save the changes to the preferences file, use the commit() method
That will look like this:
// obtain an instance of the SharedPreferences class
preferences = getSharedPreferences(prefFileName, MODE_PRIVATE);
editor = preferences.edit();
// save username String
editor.putString("username", student).commit();
To retrieve it use getString() method:
preferences.getString(username, null) where null is a default value that will be returned if username key is not found in the file.

How to get contents of SharedPreferences file and overwrite them?

I am pretty new to Android dev. I am browsing through the API here http://developer.android.com/reference/android/content/SharedPreferences.html
but I am confused about how to actually get the file contents and read or write from them.
I have this code to get the SharedPreferences object:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( MyClassName.this);
but in this case, I get the reference to sharedPreferences, but not a connection to my file which stores the preferences data.
Maybe I am not understanding the API correctly, but how am I supposed to get the reference to the file and read/write to it?
Thanks!
If you want to get values from your SharedPreferneces you have to use (this example works with Strings, but you can also call getBoolean, getInt, etc..)
prefs.getString("myString", "defaultValue"); // "defaultValue" will be returned in case "myString" wasn't saved on the SharedPreferences
to store some values you can do it like this:
prefs.edit()
.putString("myString", "newValue")
.putBoolean("working", true)
.commit();
As you can see you can edit more than one value at once..
edit() will return you an editor that you have to use in order to modify the sharedpreferences file, and when you end to edit it call commit() in order to make the changes permanently
but in this case, I get the reference to sharedPreferences, but not a connection to my file which stores the preferences data.
The SharedPreferences object has a "connection" to the file which stores the preference data.
Maybe I am not understanding the API correctly, but how am I supposed to get the reference to the file and read/write to it?
To read preferences, use the getters on SharedPreferences (e.g., getString()). To write preferences yourself:
Get a SharedPreferences.Editor by calling edit() on the SharedPreferences object
Use the setters on the Editor (e.g., putString())
Call apply() (where possible) or commit() on the Editor to save your changes
In addition, you can (and in many cases should) also use a PreferenceActivity to allow users to directly view and modify their preferences.

saving state of an android Application?

Which of the following is/are appropriate for saving the state of an Android application?
a. Activity.onFreeze()
b. Activity.onPause()
c. Activity.onStop()
d. Activity.onDestroy()
e. Activity.onFinish()
Many applications may provide a way to capture user preferences on the settings of a specific application or an activity. For supporting this, Android provides a simple set of APIs.
Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). Or it can be something that needs to be stored specific to an activity.
Shared Preferences: The shared preferences can be used by all the components (activities, services etc) off the applications.
Activity handled preferences: These preferences can only be used with in the activity and can not be used by other components of the application.
Shared Preferences:
The shared preferences are managed with the help of getSharedPreferences method of the Context class. The preferences are stored in a default file(1) or you can specify a file name(2) to be used to refer to the preferences.
(1) Here is how you get the instance when you specify the file name
public static final String PREF_FILE_NAME = "PrefFile";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
MODE_PRIVATE is the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application. Other two mode supported are MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE. In MODE_WORLD_READABLE other application can read the created file but can not modify it. In case of MODE_WORLD_WRITEABLE other applications also have write permissions for the created file.
(2) The recommended way is to use by the default mode, without specifying the file name
SharedPreferences preferences = PreferencesManager.getDefaultSharedPreferences(context);
Finally, once you have the preferences instance, here is how you can retrieve the stored values from the preferences:
int storedPreference = preferences.getInt("storedInt", 0);
To store values in the preference file SharedPreference.Editor object has to be used. Editor is the nested interface of the SharedPreference class.
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
Editor also support methods like remove() and clear() to delete the preference value from the file.
Activity Preferences:
The shared preferences can be used by other application components. But if you do not need to share the preferences with other components and want to have activities private preferences. You can do that with the help of getPreferences() method of the activity. The getPreference method uses the getSharedPreferences() method with the name of the activity class for the preference file name.
Following is the code to get preferences
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
The code to store values is also same as in case of shared preferences.
SharedPreferences preferences = getPreference(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
You can also use other methods like storing the activity state in database. Note Android also contains a package called android.preference. The package defines classes to implement application preferences UI.
To see some more examples check Android's Data Storage post on developers site.
Why won't you just use SharedPreferences?
Anyways: i'd store the data in onPause(), depending on what these data items are. You probably already know that all items that have an id assigned in the R.java are automatically saved onPause() and restored onResume()? - but this is more or less useless anyways since this data is lost after the app dies completely...
assuming that you want so save other stuff that you might want to write to an DB or file, onPause() might be a good choice. as you can see in http://xenonite.net/news/android-activity-lifecycle, after onPause() is called, the OS might kill the app if there's memory needed for other things. so the data will be lost if you'd try to save it somewhere else (e.g. onStop())
but: make sure, that this saving produces not too much overhead, since onPause() is called on several occasions (e.g. screen rotates...)

Categories

Resources