Create new preference and persist it? - android

I'm trying to create a new CheckBoxPreference under a PreferenceGroup for displaying tags. The plan is to add the tags with code like this:
for(Tag t : tags) {
pref = new CheckBoxPreference(FoodhunterCredentials.this);
boolean isChecked = wasChecked(t.getName());
pref.setTitle(t.getName());
pref.setSummary(t.getDescription());
pref.setChecked(isChecked);
pref.setPersistent(true);
Log.d("Credentials", String.format("Adding checkbox %s -%schecked", t, isChecked ? " " : " not "));
tagsGroup.addPreference(pref);
}
But after closing the activity the new checkboxes are gone. Is there a way for persisting the newly created preferences? To be clear: This is not about storing a new value in a defined preference, this is about storing a new created preference.

You can use DB to store all your tags (this is preferable).
Or, if you don't want to use DB for some reason, you can hack with SharedPreferneces in a next way:
Create empty string preference named "tags" (this should not be visible in your PreferenceActivity).
When user adds new tag, your will add tag name to "tags" string preference and save it.
For example, your "tags" string may look like "java;android;helper;europe". You'll need to make duplication checks and parsing yourself. Of cause you'll need to automatically populate your PreferenceScreen in onCreate() method with CheckBoxPreference for each tag, but you already know how to do it.
Yes, and in API level 11 (Android 3.0) and higher you can use String Sets in SharedPrefernces. See getStringSet and putStringSet for more details.

You are not able to modify the XML layout files problematically. You can store the fact that you have an extra check-box in the SharedPreferences or Database but there isn't a super-clean way of doing what you want.

Related

how to use SharedPreference among activities

I Am writing a code using SharedPreference to store username and password of a user but each time I entered information the older one in xml file are override by newer one what I have to to to get all my data?
SharedPreferences sp1=getSharedPreferences("myshared", 0);
sp1.edit().putString("name", name.getText().toString()).commit();
sp1.edit().putString("pass", pass.getText().toString()).commit();
sp1.edit().putString("age",age.getText().toString()).commit();
sp1.edit().putString("id",id.getText().toString()).commit();
It sounds like you're overwriting your shared preferences between activities. SharedPreferences are persistent like a file on disk, so you shouldn't ever have an issue with the values not being set, hence why you must be overwriting it.
You can get your SharedPreferences by doing
SharedPreferences sp1=getSharedPreferences("myshared", 0);
String name = sp1.getString("name", "noname");
String pass = sp1.getString("pass", "nopass");
...
You can determine if the name/pass was set by checking if they equal the default value (noname and nopass in this case, though it could easily be null).

android shared preference storing multiple values;

I created SharedPreference obj using following:
Note : creating number of preferences under the same pref file name
public static Sting name = "abx"; //pref file name
spo = context.getsharedpreference(name , mode_private);
editor = spo.edit(); //get the editor associated with pref obj
Map<String, String> test= new HashMap<String, String>();//create a map
test.put("1", "abc");//fill the values
test.put("2", "efg");//used map because values are stored in key -value pairs
test.put("3", "ghj");
for (String s : test.keySet()) {
// use the name as the key, and the icon as the value
editor.putString(s, nameIcons.get(s));//use the key as preference name
}
editor.commit();//commit the preferences
I have a doubt , please correct me if i am wrong , SharedPreference file with name "abz" is created and in this file preference values are stored as key - value pairs or if editor obj creates new preference file for each key , whats the use of supplying pref file name at the time of sharedprefences object creation?
Essentially, you can create multiple preference files for a given application. There are a few reasons one could imagine doing this, the best being if you had multiple accounts. You could label one set of preferences "account1" and another "account2". Just by keeping track of which account you are in, you can share code without a huge amount of complexity.
Unless you are specifically using this functionality, I suggest you use context.getApplicationContext().getPackageName() for the name, as it should be available almost everywhere.
Basically what happen inside your for each loop :-
there will be only one value stored in the preferances instead of creating SharedPreferance file with the name provided in the code for each value in the map.
Use of Giving File name during creation of sharedPreferance , so that it can be retrieved at other part of application and can acess its values.

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.

Strange behaviour for ListPreferences

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);
}

Categories

Resources