I came across an Android Question as follows. The result is confusing me.
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
SharedPreferences.Editor editor = pref.edit();
editor.putString("1", "2"); // Storing string
editor.putString("3", "4 "); // Storing string
editor.commit();
System.out.println("pref.getString() = " + pref.getString("2","3"));
Answer: pref.getString() = 3.
How does the shared preference prints this value ? Can someone please explain this ?
The first argument to get...() is the shared preferences key. The second argument is the default value to return in case there's no value by that key.
Assuming no other code has put a value with key "2" in this shared preferences file, the default value of "3" is returned when calling pref.getString("2","3").
The SharedPreference object does not print anything.
The sharedPreference stores data in key-value pairs in an xml file named MyPref in your case:
getApplicationContext().getSharedPreferences("MyPref", 0);
You put the value you want to store by calling the putXX method on the editor object obtained from the pref object by calling edit() on it:
SharedPreferences.Editor editor = pref.edit();
** putXX means put[some kind of primitive data] like int float String.
When you call putString you supply a key as the first parameter and the String value in this case as the second parameter:
editor.putString("1", "2"); // Storing string
editor.putInt("myInt", 2); // Storing integer
The commit method writes the data.
editor.commit();
The getString retrieve a string value for a key given as the first parameter and if they are no entry a default value returned which is the second parameter in this case "3":
String myValue = pref.getString("2","3")
The printing performed by calling:
System.out.println(myValue);
editor.putString("1", "2") - first argument is KEY, second argument is value.
pref.getString("2","3") - first argument is KEY, second argument is Default value (in case if such key isn't present).
In your case you've put two strings - 2 and 4 in keys 1 and 3 accordingly.
When you are trying to read string with key 2 - it is missing. So default value (3) is printed
P.s. you are using keys very similar to values - Strings containing numbers. Just put more readable keys and thing will get clearer.
Android has a page that it's very clean. Shared Preferences getString()
This method has two parameters :
key
The name of the preference to retrieve.
defValue
Value to return if this preference does not exist.
This value may be null.
So if you have this in your SharedPreferences
editor.putString("1", "2"); // Storing string
editor.putString("3", "4 "); // Storing string
And you are doing : pref.getString("2","3")
You are looking for the SharedPreferences key with a value of "2", and if it doesn't find anything you'll get "3" as a default value.
Related
While working on my app, I discovered that the only way to save a number of values (like an array) in shared preferences is by using a set. The problem is, that since the whole set thing is new to me, I don't really know how to retrieve values from it, and placing the values in dynamic text views. I would be glad if someone could show me the correct way of retrieving the values.
you can find your answer here :
Follow the link
From API level 11 you can use the putStringSet and getStringSet to
store/retrieve string sets:
SharedPreferences pref = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putStringSet(SOME_KEY, someStringSet);
editor.commit();
SharedPreferences pref = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
Set<String> someStringSet = pref.getStringSet(SOME_KEY);
The set interface has method which are as follows :
add() : Which allow to add an object to the collection..
clear() :
Remove all object from the collection.
size() : Return the size of
element of collection.
isEmpty() : Return true if the collection has
element.
iterator() : Return an iterator object which is used to
retrieve element from collection.
contains() : Returns true if the
element is from specified collection.
Example of java set interface.
Set s=new TreeSet();
s.add(10);
s.add(30);
s.add(98);
s.add(80);
s.add(10); //duplicate value
s.add(99);
Iterator it=s.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
public void buttonClick(View v)
{
EditText sd = (EditText)findViewById(R.id.sd);
EditText desc = (EditText)findViewById(R.id.description);
Spinner type = (Spinner)findViewById(R.id.type);
Spinner priority = (Spinner)findViewById(R.id.priority);
Set<String> set = new HashSet();
if(!validate(sd))
sd.setError("This field cannot be empty");
else if(!validate(desc))
desc.setError("This field cannot be empty");
else
{
set.add(type.getSelectedItem().toString());
set.add(priority.getSelectedItem().toString());
set.add(desc.getText().toString());
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref",MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putStringSet(sd.getText().toString(),set);
editor.commit();
Log.d("MyTag",pref.getAll().toString());
Intent i = new Intent(this, MainActivity.class);
startActivity(i);
}
}
private boolean validate(EditText t1)
{
if(t1.getText().length()==0)
return false;
else
return true;
}
Here in the above code, I am storing the details in the SharedPreferences with StringSet. The key is sd string and the values are desc, type and `priority'. I created a Set and put the key and the corresponding values in the set. How do I fetch the values for a given key?
The method pref.getStringSet(key, Set<String>) expects both key and the values. The key value is known but what should be put in the second argument? Tried null but it expects a type of Set.
The second parameter in pref.getStringSet(key, Set<String>) is a default value in case the preference has never been set before.
Check the documentation:
Parameters
key The name of the preference to retrieve.
defValues Values to return if this preference does not exist.
So if it has already been set, the previously assigned value is returned. Otherwise defValues is returned.
You can go ahead and put null there. The following compiles and works for me:
HashSet<String> hashSet = hashSet = (HashSet<String>) sp.getStringSet("names", null);
The second value is the default value. If Lint gives you an error when you put null, just tell Lint to ignore that error.
The second argument is a default value, if the shared preference you try to get doesn't exist or, you put a wrong name as first argument it will be set to the default value passed as second argument.
The key value is a label wich you will use to get that specific shared preference, for example:
editor.putString("name_of_your_preference", value_of_preference);
and then you could retrieve that string with:
pref.getString("name_of_your_preference", default_value);
you could use NULL only as default value
In my app, the user can add a name and an age for multiple people. Most likely it will only be around 2 or 3. I want to store these in shared preferences. I set a counter to keep track of how many people have been stored as well as to manage which key goes with which value. I took the edittext input and put it in a string and then put it into the shared preferences like so, adding on the counter so I know that is the first person and would access the person with "name1".
//this is in the class
public int count = 1;
//this is in the main
SharedPreferences sharedPreferences = getSharedPreferences("registerData", Context.MODE_PRIVATE);
SharedPreferences.Editor myEditor = sharedPreferences.edit();
myEditor.putString("Name"+count, name);
myEditor.putString("Age"+count, age);
Unless I am mistaken, that should put the string "name" into "Name1".
Then I go and try to access it in another activity with...
SharedPreferences sharedPreferences = getSharedPreferences("registerData", Context.MODE_PRIVATE);
String name = sharedPreferences.getString("Name"+count,"");
String age = sharedPreferences.getString("Age"+count,"");
Then i would update the counter before the next person would be added to change the key to "Name2" "Age2", and so on.
Whenever I try to set the strings to a textview, they show up blank. Which means its not the same String to access the key. The putString has to get the "Name1", because even when I try to access the getString("Name",""), it's still blank. Is there something I'm doing wrong or missing. Or there is a better way of doing this? Thanks.
SharedPreferences sharedPreferences = getSharedPreferences("registerData",Context.MODE_PRIVATE);
SharedPreferences.Editor myEditor = sharedPreferences.edit();
myEditor.putString("Name"+count, name);
myEditor.putString("Age"+count, age);
myEditor.apply();//returns nothing,don't forgot to commit changes
also you can use
myEditor.commit() //returns true if the save works, false otherwise.
Is there something I'm doing wrong or missing. Or there is a better
way of doing this?
If SharedPreferences key names are dynamic then you should use SharedPreferences.getAll() which return all keys available in selected preference:
Map<String, ?> allKeys = sharedPreferences.getAll();
Now iterate through allKeys to check key names and get values from Map.Entry related to key like:
for (Map.Entry<String, ?> entry : allKeys.entrySet()) {
Log.v("TAG","Key Name :" entry.getKey());
Log.v("TAG","Key Value :" entry.getValue());
}
You have to call apply() on the shared preference editor after making changes.
...
myEditor.apply();
Shared preferences however, are not meant to store content related data. Consider using more appropriate solutions like a database.
In android, i am adding string values using shared preferences, but i want to compare the value which i am going to add to shared preferences with values which are already stored in shared preferences to avoid adding duplicate values, but i am not getting how to do this?
or is there any alternate method to avoid adding duplicate values in shared preferences?
I am adding string values using following code
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putString(Name, s);
editor.commit();
In android you cannot really have duplicate value in sharedPreference because every time you change or modify a value on sharedPreference it will replace the previous with the current. So since every instance of it has a single unique key, which mean it will always be unique (in my experience every time i messed up with this keys like giving the same name key for both an Int and boolean for example i end up crashing the app or having some kind of exception)
If im wrong i hope someone else will correct me and provide you with a better answer!
I don't know whether I'm understanding your question quite well or not, but Android's SharedPreferenceshas it's own contains to check if a a key already exists or not.
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (sharedpreferences.contains(NAME)) //It already contains NAME key
On the other hand, if your worries are about a single key's value not to be repeated, just read it before storing the new value and compare themselves, no more.
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (!sharedpreferences.getString(NAME, "").equals(s)) {
// It does not have the same value, store 's'
sharedpreferences
.edit();
.putString(NAME, s);
.commit();
}
However, in this particular case I wouldn't perform this verification, just overwrite the value and that's it, as it always gonna be the same.
First get String value from SharedPreferences as oldvalue then compare with newvalue which you want to store. If String not match then save newvalue in SharedPreferences.
Try something like this
String str_newvalue = "new string here";
SharedPreferences sharedpref = this.getSharedPreferences(this.getPackageName(), context.MODE_PRIVATE);
String str_oldvalue = sharedpref.getString("key", "");
if (!str_newvalue.equals(str_oldvalue)) {
sharedpref.edit().putString("key", str_newvalue).commit();
}
Do this
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if(restoredText.matches(your string))
{
// do nothing
}
else
{
//save your data
}
}
Here is the code i tried:
SharedPreferences.Editor prefEditor = sharedPreferences.edit();
int balance = sharedPreferences.getInt("balance", 0);
prefEditor.putInt(balance, balance1);
prefEditor.commit();
From the comments beneath your question, I understand that you simply wish to update a value within sharedpreferences. Your first line is fine:
SharedPreferences.Editor prefEditor = sharedPreferences.edit();
This next line is then optional. Use it if you want to get at the existing value held under the key "balance" before you replace it. Otherwise it is not required and has no bearing on the 3rd line of code which replaces "balance" with a new value.
int balance = sharedPreferences.getInt("balance", 0);
Then I think your 3rd line should become:
prefEditor.putInt("balance", balance1);
That will replace the value held under the key "balance" with whatever value is held in balance1. Notice the quotes around "balance" that you did not have in your original code.