SharedPreferences vs. Private File - android

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.

Related

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

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.

Shared Preferences differences

1) What is the difference between
PreferenceManager.getDefaultSharedPreferences(context)
and
getSharedPreferences(name, mode)
2) And what does each of them do?
3) And how can I make a setting screen (Activity)?
1) You can have multiple SharedPreference files (so they are called SharedPreferences). The argument name of method getSharedPreferences(name, mode) specifies the the name of SharedPreference file to handle.
PreferenceManager.getDefaultSharedPreferences(context) returns the default SharedPreference file having default name and mode. Default name is based on your app's package name (as packagename_preferences.xml) and default mode is MODE_PRIVATE.
If you just want to use a single SharedPreferences file, PreferenceManager.getDefaultSharedPreferences(context) is concise to use.
2) With SharedPreferences you can save some key-value data.
3) Your last question: how to make a setting screen? is too wide topic to answer here. However, I suggest that using PreferenceActivity or PreferenceFragment you can manage a SharedPreferences without handling SharedPreferences directly.

Can I have a main Map file in my Activity and share it with the Fragments?

I am currently using SharedPreferences for both my preferences and my data. Realizing that getting all of the values for my data out via prefs.getAll() actually gets both of my SharedPreferences which is incredibly annoying.
What is the best route for my data. It is key-value with the keys being dates and the values being floats. (Actually ideally I'd have two floats for every key, but I could traverse two.)
Can I make a Hash Map in my activity and inflate/deflate as normally and send it to my fragments as I need the data?
Your question is asking a few different things, so I'll try answer them all.
For storing data that is too complex for shared preferences, you should look into using an SQLite database. There are some good libraries that make it very simple - check out ActiveAndroid or OrmLite.
If you want to stick with shared preferences, but want to solve the issue of getAll returning the preferences and the data, you can actually create 2 separate sharedpreferences. There is a method getSharedPreferences (String name, int mode) which takes a name. Use the default shared preferences for your preferences, and create a shared preference with a different name for your data.
As for sending data to your fragments, you can use a Bundle. Bundles take all sorts of data, and serializables as well, so that should be no problem. Put your data into a bundle and pass it to your fragment when its instantiated.

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