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.
Related
Note this question is NOT about obtaining the contents of a SharedPreferences object if the keys are not known, it is about if its possible to obtain the SharedPreferences themselves if its name is not known.
Suppose there are SharedPrefreferences collections with 'file names' "something-a", "something-b", "something-c". Then is it possible to determine that there are 3 sets of SharedPreferences object available and to be able to get them when only the "something-" part of their name is known?
I guess not but hopefully there is.
I'm not going into the reasons behind the requirement except to say there is a requirement to update an app to Marshmallows permissions model and it needs to be capable of reading preferences files written by older versions of the app where the preferences name is "something-imsi". If the user has not granted the relevant permission on Marshmallow then the app does not know the imsi and thus I am trying to find out if its possible for the app to read the shared preferences when it doesn't know the full name.
You can retrieve all preferences with SharedPreferences.getAll() and iterate over this collection for string keys that match your pattern. For example:
SharedPreferences prefs = ctx.getSharedPreferences(PREFS_NAME, 0);
Map<String, ?> pairs = prefs.getAll();
for (Map.Entry<String, ?> entry : pairs.entrySet()) {
// Check for your string pattern here...
}
This answer assumes you have one shared preferences file with keys matching the pattern described in the question. If that's not the case, and you have multiple dynamically named shared preferences files matching the pattern, it's a harder problem. You might make some progress by iterating over the files in Context.getFilesDir()
I don't think it is possible to get the list of file names of the preferences available. Though if you know the file name and then you can get an instance of the SharedPreferences and use getAll method to get all the keys present in that set of preferences.
Here is the documentation:
https://developer.android.com/reference/android/content/SharedPreferences.html#getAll()
Example:
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, 0);
Map<String, ?> map = sharedPreferences.getAll();
for (Map.Entry<String, ?> e : map.entrySet()) {
String key = e.getKey();
// this is the key that is present
}
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).
I have released my app to the market and I'm preparing an update.
However, I wanted to refactor the key name of some shared preference but retain the current value on the user's device. Another thing is that I also want to delete the old key name (so the SharedPreferences file is not polluted with unnecessary keys.
How can I achieve this without any hassle to my users?
Create an array of all of your preference keys
Create an array of all the new preference keys
Then create and array of all of their values.
Then call SharedPreferences.clear(). This will completely remove all keys and values from the preferences.
The step through all values and place them back into the SharedPreferences by their new key.
in my app the first activity is a sign in page. In the edit boxes i am typing the user name and password. Those values are been move to an api and in return i am getting the userid from the server as an xml file.
I am parsing the xml file and storing the value in shared preferrence as follows
SharedPreferences.Editor IdEditor = Id.edit();
IdEditor.putString("useridValue", chap.getid());
IdEditor.commit();
And in the next time when the user opens the app i want to check whether it is already signed i or not. How to check this using the value stored in Shared preference
is your Id class extending SharedPreferences ?
maybe
String userId = Id.getString("useridValue");
If your preference is stored in the default preference then you can
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String userId = prefs.getString("useridValue");
on a side note you shouldn't really use a capital I on the IdEditor variable it should probably be idEditor
Check whether this entry already exist in shared preference, using:
id.containskey("useridvalue")
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.