Retrieving values from a SharedPreferences string set - android

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

Related

SharedPreference StringSet to Array Order Issue

Please be patient while I explain my issue:
1) I am storing my preferences via a StringSet as follows:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
// Create a new Arraylist with the details of our details
ArrayList <String> newCityFareDetails = new ArrayList<String>();
// Store various values
newCityFareDetails.add(0, String.valueOf(cloneFare.value1()));
newCityFareDetails.add(1, String.valueOf(cloneFare.value2()));
newCityFareDetails.add(2, String.valueOf(cloneFare.value3()));
newCityFareDetails.add(3, String.valueOf(cloneFare.value4()));
newCityFareDetails.add(4, cloneFare.value5());
// Only value 5 is a string, rest are all floats
// Convert to a hashstring, give it the name of our value
Set<String> set = new HashSet<String>();
set.addAll(newCityFareDetails);
editor.putStringSet(extras.getString("startCity"), set);
// And write it to storage
editor.commit();
Now, I'm trying to read it as follows:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE);
Set<String> tryCityFromPrefs = prefs.getStringSet(currentCity, null);
if (tryCityFromPrefs!=null){
// Crude code, but we convert the preferences into a String array
String[] values = tryCityFromPrefs.toArray(new String[tryCityFromPrefs.size()]);
myFare = new Fare(Float.parseFloat(values[0]), Float.parseFloat(values[1]),
Float.parseFloat(values[2]), Float.parseFloat(values[3]), values[4]);
}
Now, problem is that the myFare is not getting initialized properly because the values in the array are scrambled. i.e. the String value that was at the last position when we save is now in the 2nd position. Is this something to do with Sets to String conversion? Or am I missing something obvious?
A Set does not guarantee order. While there are specific Set implementations (e.g., LinkedHashSet) that are ordered, that's not what SharedPreferences uses.
Your options are:
Change your app to not care about the order.
Save the data in SharedPreferences some other way. In this app, for example, I use JsonReader/JsonWriter to save an ArrayList into a single String value.
Save the data in some other fashion (e.g., JSON file, SQLite database with a sequence number to maintain order).

How to store an arraylist which has content class (class in project)?

I want to store an ArrayList<class> in shared preference. But the error showed up in editor3.putString("Array", nama);. I guess the error caused by putString. What sould i do?
Should I used another method to storing arraylist ?
ArrayList<Class> nama = new ArrayList<Class>(9);
nama.add(dragsandal.class);nama.add(Terimakasih.class);
nama.add(Ludah.class);
nama.add(Permisi.class);
nama.add(Tolong.class);
nama.add(Maaf.class);
SharedPreferences pref3 = getApplicationContext().getSharedPreferences("Array", MODE_PRIVATE);
SharedPreferences.Editor editor3 = pref3.edit();
editor3.putString("Array", nama);
editor3.apply();
You should use putStringSet(Set<String>) to store sets (Lists with unique elements). SharedPreferences do not provide a method to store lists directly.
You can easily convert your list to a set using e.g. new HashSet<String>(yourList);
If you need to store a list, you can serialize your list to a String, e.g. by using Gson and storing the json value. Then putString(json) would be correct.
First I don't think there is a way to store lists in Shared preferences. Second it is not a good idea. In your case,I would consider using Sqlite database. It would make things easier.
You can't store a Class type object in SharedPreferences. Also you can't store Lists. If you really need to, you can store the full name of the class object as a String. Then when you read the value back you, you can use Class.forName() to convert that string back to a class. It seems weird, but you can do it.
You could try this to save and restore a set of class names:
Set<String> set = new HashSet<String>();
set.put(Terimakasih.class.getName());
set.put(Ludah.class.getName());
set.put(Permisi.class.getName());
set.put(Tolong.class.getName());
set.put(Maaf.class.getName());
SharedPreferences pref3 = getApplicationContext().getSharedPreferences("set", MODE_PRIVATE);
SharedPreferences.Editor editor3 = pref3.edit();
editor3.putStringSet("set", set);
editor3.apply();
Set<String> strings = pref3.getStringSet("set", Collections.emptySet());
Set<Class> classes = new HashSet<Class>();
for (String s : strings) {
classes.put(Class.forName(s));
}

Increment shared preference key after adding 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.

Need to get all sharedPreferences but in correct order of insertion

I need some help in getting all sharedPreferences (keys & values) from my custom preference, but in order that they were originally inserted in the preference file. I currently have the below code but the problem is because getAll() returns a map the order changes.
public List<String> getPrefValues(String pref, Context context) {
Map<String, ?> allEntries = context.getSharedPreferences(pref,
Context.MODE_PRIVATE).getAll();
List<String> command = new ArrayList<String>();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
command.add(new StringBuilder(entry.getKey())
.append(":")
.append(entry.getValue()).toString());
}
if (command.isEmpty()) {
return null;
} else {
return command;
}
}
You can store your desired attributes in a LinkedHashSet, because there,
The iteration order is the order in which entries were inserted
Sets are stored in preferences with:
Set<String> mySet = new LinkedHashSet();
insertAttributes(mySet);
SharedPreferences myprefs = getPrefs();
myprefs.edit().putStringSet("myKey", mySet).commit();
This is also applicable to a map structure: simply create one set, that contains all keys, and one, that contains the values.
There is NO facility in SharedPreferences for tracking insertion time. It would be better if you can figure another way (external to SP) to track this value.
Bottom line, there is no way within the current SP structure to understand 'insertion time'.
You can use the prefix as numbers for the keys when you put in the order you want to get them out.
For example: 00data, 01foo, 02cree.
Then put the Set<String> returned from getStringSet in an Array<Set> and sort it -
Set<String> set = prefs.getStringSet(key, new HashSet<String>());
Array<String> a = set.toArray();
java.util.Arrays.sort(a);

How to avoid adding duplicate values in shared preferences in android?

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

Categories

Resources