I am working on implementing the preferences for our application. I know how to display preferences UI and how to read/write values using SharedPreferences. In our app, I need to handle two sets of preferences and I would like to ask about this issue, one comment in the Android documents in particular.
The documentation for Preference.getSharedPreferences() has the following comment under the Return values section:
Returns The SharedPreferences where this Preference reads its value(s), or null if it isn't attached to a Preference hierarchy.
I would like to ask how it is possible to attach a SharedPreferences to a particular Preference, be it EditTextPreference or others. In other words, how does the persistence code in a Preference know that it should store the user input in one particular SharedPreferences object and not the other?
To explain my question further with an example, suppose I have the following:
SharedPreferences prefs1 = getSharedPreferences(file1, mode);
SharedPreferences prefs2 = getSharedPreferences(file2, mode);
My question is what API I should use so that prefs1 is used by the Preference objects' persistence code and not prefs2.
The target is Nexus One, running 2.3.4.
Maybe the answer is obvious but I could not find it after reading the documentation and searching the web. Thank you in advance for your help.
In other words, how does the persistence code in a Preference know that it should store the user input in one particular SharedPreferences object and not the other?
Preference uses PreferenceManager's getSharedPreferences(), which eventually routes to getDefaultSharedPreferences().
You are welcome to create your own Preference subclasses that change this behavior, but since the preference screen system may not be designed to handle multiple SharedPreference objects, there's a chance that your preference changes might not get persisted.
IOW, I encourage you to reconsider:
In our app, I need to handle two sets of preferences
Related
I have an android application that has uses few serializable classes
(I can store and load them in JSON format using Google Gson library and it works like a charm).
Now I want to provide way for user to edit those objects in fashion similar to PreferenceActivity - they contain few strings, ints and doubles and PreferenceScreen just seems ideal for editing them.
Is there a way to 'abuse' PreferenceActivity to provide UI for editing my objects without actually storing data in shared preferences?
For example - if there was some callback to override that is called just before saving data, I could extract data, assemble my object and somehow prevent Android from messing with preferences?
SharedPreferences is an interface, so you should be able to provide your own implementation that stores data however you like. But the PreferenceManager used by PreferenceFragment only has a setter that takes a file name, not a custom implementation of SharedPreferences.
I looked into the source and found a roundabout way to use your own implementation. PreferenceFragment uses its hosting Activity as the Context for constructing a PreferenceManager. PreferenceManager subsequently calls Context#getSharedPreferences(String, int) to get the SharedPreferences that it will use. Therefore, you can override getSharedPreferences in the activity hosting your PreferenceFragment and return your custom implementation. Implementing SharedPreferences could be rather complicated since you'll also have to implement SharedPreferences.Editor, but it's doable. And if there's any chance of your overridden getSharedPreferences being used anywhere else, you should document that it uses a different backing store.
In the Android O preview, there's a new interface called PreferenceDataStore and a new setter in PreferenceManager that takes an instance of that interface. PreferenceDataStore looks much simpler to implement than SharedPreferences. But as I write this, most retailers are still selling L and M devices, so who knows when we'll see O.
First I would think if I really want to present objects editing with preferences UI since it might confuse a user.
If you still decide to go this way you can achieve it with:
Serialise every object in separate shared preference file and use preference activity how it is designed
Write own PreferenceManager and use reflection to replace private field in PreferenceActivity
The first one is straight forward and rather simple to implement, might have some performance implications. The second one might get tricky and probably requires more code to write.
I would still advice to revise decision to "re-use" PreferenceActivity for such case.
I am designing a simple application that will count how many times a user has tapped on a imageView. My question is what would be the best way of saving and reading this file. Any suggestions? I am thinking something like using Parse.com's local database. I have tried it, but I could not get it working the way I wanted. I am still a beginner, so please not so fancy suggestions.
Try to save data in SharedPreference. SharedPreference works like database for application on device that will be stored until any one has unistall app from device.
To create sharedPrefernce-
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
To store data -
prefs.edit().putInt("key", int_value).apply();
To retrieve data-
// use a default value
int l = prefs.getLong("key", default_value);
Simplest options is always thebest option, go with shared preferences
Here is simple tutorial from google http://developer.android.com/training/basics/data-storage/shared-preferences.html
It will store your data in application local file. Take a note of that there are different shared preferences in example getPreferences() will return file specific for activity you used this method. While getSharedPreferences() will return application global file.
I would like to be able to save my users session or sharedPrefrences in a way that if the user kills the application and you start it it would look like this.
Button one = Start Activity with Blank Preferences
Button Two = List of Saved Sessions of Preferences and once clicked all put into the Starting activity.
Is this possible and if so how would I go about doing that?
Thank you!
Yes you can do that and it is good to use sharedPreferences if you just have to store some session variables. But if it is more, then go for database.
Do clear sharedPrefences in your application you need to do this:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(activity);
Editor editor = settings.edit();
editor.clear();
editor.commit();
For reading the preferences, you can keep a sharedPreference with the count for the seesions. While saveing the prefences, always save with the strings session1, session2, session3 etc. So, while accessing them based on count, prepare a loop and form the string and access all the session variables and show them.
The reason why I didnt suggest you to do getAll() for sharedPreference is that, you may save few other things in sharedPreference. So by forming strings yourself, while reading you can just get the sessions and not other data saved in sharedPreference.
I hope you understand what I meant
Is this possible
I would say yes, depending on exactly what you mean.
if so how would I go about doing that?
SharedPreferences has a couple different functions to do something like this, depending on exactly what you want. You can get a Map of all preferences that are stored after clicking Button2 with getAll() or a set of preferences with a certain String such as "userName" or something similar with getStringSet(). Play around with the functions it offers and see if it gives you what you are looking for.
Also take not of the warnings of these functions
Note that you must not modify the set instance returned by this call. The consistency of the stored data is not guaranteed if you do, nor is your ability to modify the instance at all.
I have created a service that writes some information about a widget once a user places it on home screen(the info is picked up from the confutation activity)..i also write down the number of widgets the user has set up.
Once the user removes the widget i delete that info in the shared preferences.
What i have experienced is that if user places for example 2 widgets, then removes one, then places one again, doing all those actions fast, the shared preferences file gets inconsistent values in it. Sometimes it works ok but most of the time i get stuck with wrong values in it.
I am using apply(), i've tried with commit but same thing happens.
The values i store in the shared preferences are crucial for the system to work, without it the widgets are useless since they are backed up by info from internet based on the user configuration which is written in preferences.
Is switching to a database solution more reliable or any other viable solution which will fix this "race condition"? (maybe forcing my own mechanism of synchronization, but as far as i've understood from docs, apply() is already synchronized, and the read/write should first go to RAM which should make it fast and i shouldnt be experiencing any problems like this since the user cant physically manage to delete a widget and place a new one faster then 2-3 seconds top!)
Try using the synchronized keyword in working with the SharedPreferences itself. For example, here is a method that could be used when setting an application String in the SharedPreferences of an Android app:
public synchronized static void setAppString(Context context, String pref,
String val) {
SharedPreferences sp = context.getSharedPreferences(
APP_PREFS_UNIQUE_ID, Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString(pref, val);
editor.commit();
}
For few/simple key-value pairs, you might not need the overhead of a database paradigm.
I am looking for a way to create dynamic preferences where I don't need to hard code the preference key and I could have a variable number of preferences.
Basically, my application will let the user create a multiple number of profiles and each of these profiles will save custom values for a fixed number of preferences.
So this way, the user does not have to change the preferences every time he wants this app to run differently, he can just switch the profile.
One way I think will work is by subclassing all the standard Preference classes and calling their setKey method with my custom preference key, containing the profile name, but this is ugly.
So is there a cleaner and more standards compliant way to do this?
Regards,
Dhruwat
You can save different preferences in a different file for each user using the getSharedPreferences method:
getSharedPreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter.
That way, you can do something like this:
SharedPreferences settings = getSharedPreferences("prefs_user_"+user_id, 0);
// from now on you can use use the normal way to set or get the preferences
I'm assuming you are using an id in order to identify them users.