Strange behaviour for ListPreferences - android

Here's the problem I'm facing : In my application I have several preferences stored in sharedPreferences that record different settings of the application. These are some strings. Because I want the application to start with some default values for these settings , in onCreate I construct a "Setting" object for each setting in which I check to see if the sharedPreference associated is null and if it is so I put the default Value in the sharedPreference.
Setting(int setting, String default)
{
storedPref=sharedPref.getString(getText(setting),null);
if(storedPref==null)
{
SharedPreferences.Editor edit=sharedPred.edit()
edit.putString(getText(setting),default);
edit.comit
}
}
The views associate to these settings are ListPreferences (). When first opened the application , they are supposed to display a list of options , in which the selected one is the default ,but it happens sometimes no options is selected , not even the default one, which is not intended.
The listPreferences are constructed in xml , by setting an array to the "entries tag" and to the "values tag" . I'm not really sure , what should I pass to the constructor of the Setting object for the default , a member of the entries array , or a something from the values one !!! If I pass a member of the entries some will Listpreferences will have the expected behaviour and some will have the one described above. If I do otherwise and pass something from the values array , the same thing happens ! Has anyone any ideea why this strange behaviour ?

You should check out the preferences file, and recognize the key and format is used by our ListPreference, then you use the same key value pair in your SharedPreferences.Editor
you will find your prefs files in the following folder
/data/data/com.your.package/shared_prefs/
you get there by running in console:
adb shell
cd /data/data/com.your.package/shared_prefs/
ls

Since the second parameter of SharedPreferences.getString() is the default value that will be returned if the key is not present, you could just as easily write
Setting(int setting, String default)
{
storedPref=sharedPref.getString(getText(setting),default);
}

Related

Why does SharedPreferences need two keys?

I'm trying to build a single object that handles all my SharedPreferences, since they are mostly used in the whole app, and I don't quite Understand why it takes two keys to get a value.
The call looks like this:
context.getSharedPreferences(FirstKey, Context.MODE_PRIVATE).getString(SecondKey, default)
I get that its basically built up as a two dimensional array.
The FirstKey gives me a collection of key-value pairs I can use my SecondKey on to get my value. And I get that If I have dozens of SharedPreferences this might come in handy to manage them and prevent mixups/unwanted overwriting.
But is this necessary If I only have like 10 preferences I save anyway or is it reasonable to just use one FirstKey for all of my preferences?
But is this necessary If I only have like 10 preferences I save anyway
or is it reasonable to just use one FirstKey for all of my
preferences?
So for this case you can avoid the use of that FirstKey by using getDefaultSharedPreferences() like this:
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
editor.putString("myKey", "myValue");
editor.apply();
or read already set preferences:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String myPref = prefs.getString("myKey", "myDefaultValue");
I guess it is to encapsulate, organize and manage better groups (first key values) of data you want to store (second keys values). So in case you want for example to retrieve all settings preferences you can group them by a Settings file (first key). Or in case you would like to delete all stored values regarding a user preferences (preferred language, preferred currency.. ) then you can organize those data within a "UserPref" file (first key) and then you can iterate within it to either delete all of them when you logout or whatever pogic you see useful for your user experience.
First key
Retrieve and hold the contents of the preferences file
Second key
Retrieve and hold value in this file
You can use only your "FirstKey" for all your preferences and normally dev us it like this only. You can create multiple instances of shared preference by changing the "First key" at the time of getSharedPreference(). Suppose you want two different shared preference for two different modules in your project then change the "FirstKey" parameter, in this case, you have two be careful while storing and fetching data from preference as you have two different shared preference.
As you rightfully stated, the first key represents a group of key-value pairs (which is actually very similar to a single file) and the second key helps you fetch the values in that file/group.
I personally believe this design is great especially in cases where you may want to separate all your values into different categories. If your app is "small", you can save all your values in one single file/group. Otherwise, you can split all your values into separate files/groups.
I hope this helps.. Merry coding!

Trying to import a SharedPreference of values?

I used SharedPreferences in one activity to basically store a bunch of data in a HashMap like method. In particular, app names (String) and their respective sorting as either a Category 1, 2, or 3 app. Stuff like:
editor.putString("Cut the Rope", "Category 1");
In another activity, I want to use this SharedPreference to create an ArrayList of only the Category 1 apps. Here is how I thought this could be done:
ArrayList<String> cat1Apps = new ArrayList<String>();
SharedPreferences stored = getSharedPreferences("Sorted Apps", 0);
SharedPreferences.Editor editor = stored.edit();
Map<String, ?> mappedPreferences = stored.getAll();
for(Map.Entry<String, ?> entry: mappedPreferences.entrySet()){
if(entry.getValue().toString().equals("Category 1")){
cat1Apps.add(entry.getKey());
}
}
For some reason though, this isn't working. I'm taking these app names and then later there's some code that creates a GridView display of Category 1 apps. If I just define cat1Apps.add() a bunch of time, this works fine, but if I try to import through the SharedPreferences as above, it doesn't create the GridView.
The problem here is that editor.commit() was never inserted after after adding the Strings to SharedPreferences so they were never saved. Otherwise, this code to retrieve the SharedPreferences was correct.
Some debug links as asked for by the OP
This one isn't necessarily about debugging but has some good information
Eclipse Debugging
YouTube video onDebugging- Note I just scrolled through some of this but looks like it could be helpful
Also not that when they say, "Right click and click toggle breakpoint", you can also double-click in the margin and you should see a green dot which means there's a breakpoint there. Double-click the green dot to remove the breakpoint.

Is there simple way to create user defaults values for TextView in Android?

I'm looking for simple way to create user defaults values for TextView in Android: I need the standart solution that user is seeing the previous value, that was entered by him to the TextView. Sure, there is way to store value of TextView at somewhere and then read it again while starting activity, but, may be, there is any simple tool to get what I wish ?
You can use SharedPreferences to store previous values and then get previous values from shared preferences to set as default values
Just to get your question correctly:
You want to present the values the user selected/set in his last visit?
You can save those values in the SharedPreferences - That's what they're made for.
You can give the google prediction api a try.

Android storing string array

I've been looking for over the past day and a half at several websites about how to store strings/string arrays/etc. and I can't seem to figure it out. I'm not sure if I'm just not quite comprehending how to implement data storage..or what. But here is my problem, simply put, I have two activity pages (we'll name 'A,B' respectively) . All I want to do is get a string from a text view in Activity B, store it in an array, and then have it accessed by clicking a button in Activity A.
I know it is simple, but I hit a block for some reason... I am trying to use SharedPreferences but how would I obtain the string from Activity B, store it in a global array, and let it be accessed by a different activity (Activity A) ?
Just store it into shared preferences (usually in onPause()):
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString(GAME_STATE, writer.toString());
editor.commit();
in one activity and load in another (usually in onResume()):
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
String jsonState = preferences.getString(GAME_STATE, null);
And nothing prevents you from using public static variables
You can't store an array directly in shared preferences, but you can store a set.
See putStringSet and getStringSet. You can add all the items from your array to a LinkedHashSet (as long as they are unique) if you wish to store them in SharedPreferences. See Konstantin's answer for the general idea on how to use SharedPreferences.
Yes you can obtain and store value in global array but you will loss everything once you close the application. So its better you create a table and store/get values from the table whenever you required.
Here is an example for creating SQLite example.

Android - ListPreference save to file or on entry click listener?

My application has a preference file, "settings", which contains 10 key/value pairs.
The keys act as titles for the user, and the values are URL's
Both the key and the value are changeable by the user e.g. the first setting looks something like "example" with the value "example.com", when a user changes that setting, the key also changes. So the first setting would become "different_example" with the value "different_example.com". All stored under the "settings" preference file.
I have been managing this so far, by opening a dialog containing the current key/value pairs in an ArrayList that has an onItemClickListener that pops up a second dialog containing another ArrayList of the possible key/value pairs. When the new item is clicked, I remove the current setting, add the new one, then re-populate the initial ArrayList with the new settings. This works and allows both the key and value to be simultaneously changed and updated, however it looks awkward with the two dialogs.
I'd like to switch this all over to ListPreferences. As in, have ten different ListPreference items, one for each setting, that when clicked opens the listing of all possible entryValues, and when selected, updates the key from the entry name, and the value from the entry value, and saves this under the same "settings" file. I'm not seeing how to save ListPreferences to a specific file, so that I can call
SharedPreferences settings = getSharedPreferences("settings", 0);
anywhere, though
I've also been looking for some kind of click handler for what to fire when an entry is selected so I can manually update the "settings" file, but not having any luck. Does such a thing exist? Or is there another way for me to do this?
Edit: I can use OnPreferenceChange to manually set the new value, but this doesn't return the value name, e.g. the value used in the human-readable list. Any ideas on how to get that?
See if this can give you a jump start: How do I get preferences to work in Android?
If you customize your ListPreference and come across something like this How to make a Preference not save to SharedPreferences?
Ahh, well this seems incredibly backwards, but what I've done is set each ListPreference to have an onPreferenceChangeListener, and each entryValue for the ListPreference to contain the name as well as the value separated by an arbitrary string. Then in the onPreferenceChange, I can reference the new value (which now also contains the new key) turn it into a String[] split at the arbitrary separator, then assign the String[] 0 index as the new key, and the 1 index as the new value by using SharedPreferences.Editor after removing the original setting.
Unless there's some way to return the Entry name from the ListPreference's entryValues array, or to specify ListPreference to save to a specific settings file, neither of which is documented, then this will probably be the best solution for me.

Categories

Resources