How to make shared-preferences globally available in android application? - android

I want to get some key-values throughout my application, in iOS we have user-defaults, how can we make preferences behave like that i.e. accessible from any activity?

You can create a new shared preference file or access an existing one by calling one of these methods:
getSharedPreferences() — Use this if you need multiple shared preference files identified by name, which you specify with the first parameter. You can call this from any Context in your app.
getPreferences() — Use this from an Activity if you need to use only one shared preference file for the activity. Because this retrieves a default shared preference file that belongs to the activity, you don't need to supply a name.
For example, the following code accesses the shared preferences file that's identified by the resource string R.string.preference_file_key and opens it using the private mode so the file is accessible by only your app:
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
You can read the official guide on Save key-value data.

Related

What does the String parameter in getSharedPreferences() do?

Edit: The provided "duplicate" doesn't solve my question as it doesn't fully answer my question. (Info about the second parameter is missing).
This question is intended to clear out the information for new Android developers and not to solve my own problem. Please reconsider the downvotes.
So, here's the method:
getSharedPreferences(string, Context.MODE_PRIVATE);
I can't really get what the first parameter does. What does it do? Why is there a first parameter if when we save something to SharedPreferences we use a key?
As documented in the Android Developer Documentation for getSharedPreferences(), the full signature for the method is:
SharedPreferences getSharedPreferences (String name, int mode)
The formal signature provides the name of the first parameter, name, which is information useful to the answer. The name parameter is the base name (without file extension) of an XML preferences file located in the private storage of the app.
For example, this call will return the SharedPreferences instance to allow reading and writing the app's settings.xml preferences file:
SharedPreferences sharedPrefs = getSharedPreferences("settings", Context.MODE_PRIVATE);
As indicated in the official documentation, the returned SharedPreferences object is a single-instance object, shared between all callers for the same file name. This means that a given call does not necessarily imply file IO to read a given preference, but may incur thread synchronization between threads in the same app.
The specified file will be created if it doesn't already exist prior to calling getSharedPreferences(). The second argument, mode, is the mode to use when creating the file, and should be set to Context.MODE_PRIVATE (or it's integer value 0); other mode values are not documented as allowed, and should not be used. As when creating any file, indicating a mode of Context.MODE_PRIVATE will locate the file in the app's private storage, as is expected for use with getSharedPreferences().
An example of writing a value (999) to a key (setting) in a SharedPreferences instance is this:
Context context = getActivity();
SharedPreferences sharedPrefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putInt("setting", 999);
editor.apply();
Reading the value from the same key is done this way:
Context context = getActivity();
SharedPreferences sharedPrefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
sharedPrefs.getInt("setting", 0);
Additional usage information can be found in the Saving Key-Value Sets page in the Android Getting Started Guide.
Note that getSharedPreferences() is a generalized version of getPreferences(), which is often the better choice for common application preferences. Aside from the ability to specify which preferences file to use with getSharedPreferences(), both methods are otherwise identical in function and behavior. According to the getPreferences() documentation, it simply calls getSharedPreferences() with "this activity's class name as the preferences name" (the first parameter to getSharedPreferences()).
The String parameter in getSharedPreferences() is the file name that stores the keys and values that you provide. For example:
SharedPreferences.Editor s = getSharedPreferences("Pref",Context.MODE_PRIVATE).edit();
s.putInt("someKey",0);
s.apply();
Will make an output file in your app, called Pref, which contains the keys you'll enter.

SharedPreferences vs. Private File

In my app, I use a PreferenceActivity framework to store persistent data. My intent is to create multiple save files, all of which may be accessed by the Preferences, but only one at a time.
When is it better to use a private file generated by Context.openFileOutput() and when is it better to use SharedPreferences?
EDIT
My data exists solely in primitives.
Normally developers use a preference file that is common to an entire app using getDefaultSharedPreferences.
However, Android has a getSharedPreferences(String name, int mode) method in Context. You could use this to have multiple preference files, in your case - save files, by using unique names passed into the name parameter.
Regarding volatility, you can force the preferences to save by getting an Editor via edit() and then calling commit().
Make sure to note that the SharedPreferences will indeed be shared based on the name:
Retrieve and hold the contents of the preferences file 'name', returning a SharedPreferences through which you can retrieve and modify its values. Only one instance of the SharedPreferences object is returned to any callers for the same name, meaning they will see each other's edits as soon as they are made.

Can I perform database specific operation using android.preference package?

I need a database in which I can store data and get data whenever I need.
Is this possible with android.preference package.
I do not want to use sqlite database
regards
According to Shared Preferences | Android Developer Tutorial (Part 13) by Sai Geetha M N,
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.

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

Read SharedPreferences when you haven't set the name of the file

When you createa a PreferenceScreen on Android, your application creates a default SharedPreferences file for the settings.
I want to read this name, or get a reference without specifing the name.
Currently I use:
SharedPreferences prefs = ctx.getSharedPreferences("prefs", 0);
SharedPreferences.Editor ed=prefs.edit();
But this returns another copy of the preference. When I checked the folder in /data/data/myapk/shared_prefs
I see two files, one named prefs.xml and the other is my [package name]_preferences.xml (this was created by the PreferenceActivity);
How do I get an instance of the shared preference with the usage of the default file name, so I should not mention a name for it?
I'm fairly sure you want PreferenceManager.getDefaultSharedPreferences(Context context).

Categories

Resources