Increment shared preference key after adding value - android

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.

Related

editor.remove() in sharedpreferences not removing the key

I have experienced a strange behavior that does not make any sense to me.
I have managed to save a value of temperature in sharedpreferences in a Java Class that is not an activity by doing this:
The method getContextOfApplication() is the one I am using in my Java.Class where i am putting the value of a temperature in a String and storing it in sharedpreferences as "temperature".
This method is declared in my MainActivity like this:
public static Context contextOfApplication;
public static Context getContextOfApplication() {
return contextOfApplication;
}
This method getContextOfApplication(); is the used in all assosiacions with sharedpreferences, in Mainactivity and in my Java.Class
tempParsed = Jobject.get(("temp")) + "";
SharedPreferences tempSettings = getSharedPreferences(getContextOfApplication());
SharedPreferences.Editor tempEdit = tempSettings.edit();
tempEdit.putString("temperature", tempParsed);
tempEdit.apply();
And later I recieve this value of the key "temperature" in my MainActivity like this:
SharedPreferences fetchSettings =
PreferenceManager.getDefaultSharedPreferences(getContextOfApplication());
String Temp = fetchSettings.getString("temperature", "");
And I can use the stored temperaure with the String Temp.
So far so good.
Later on in my code I wanted to delete this string in that is saved in sharedpreferences with the key "temperature".
Easy I thought...
First I called this code when I wanted to delete the value / values
SharedPreferences fetchSettings =
PreferenceManager.getDefaultSharedPreferences(getContextOfApplication());
SharedPreferences.Editor editor = fetchSettings.edit();
editor.clear();
editor.apply();
But this code deletes ALL information that is stored, so I obvously didn't want that.
That's why I tried to change this line:
editor.clear();
editor.apply();
To this:
editor.remove("temperature")
editor.apply();
But this didn't work!!
Now you are probably wondering "Are you sure that is what your key is named?"
I added this code to read all entries that were stored in the defaultsharedpreferences:
Map<String, ?> allEntries = fetchSettings.getAll();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
Log.d("mapvalues ", entry.getKey() + ": " + entry.getValue().toString());
}
AND THE LOG SHOWS "temperature:" as the key....
Why is editor.clear(); working but editor.remove("key") is not?
According to the docs you need to call commit for the changes to happen:
editor.remove("temperature").commit();
Solved
You can try this code for remove single preference:
Prefs.remove("my_custom_key");
Don't forget to import library:
import com.pixplicity.easyprefs.library.Prefs;
This code worked for me Beautifully.

Android get shared preferences from different files

in my android application i've got 4 differents shared preferences files, each one with his preferences.
To access and modify them i use a setting activity.
I've got some preferences which are not in this files but are in DefaultPreferences.
How can i read each shared preference from this files one by one?
I found this code but i can't get it works.
SharedPreferences prefs_clima = getSharedPreferences("prefs_clima",MODE_PRIVATE);
Map<String,?> keys = prefs_clima.getAll();
for(Map.Entry<String,?> entry : keys.entrySet()){
Log.d("map values",entry.getKey() + ": " +
entry.getValue().toString());
}
I always get zero preferences when reading.
follow this method and try to retrive the values
// retrive sharedpreference
SharedPreferences sharedPref = getSharedPreferences("prefs_clima", Context.MODE_PRIVATE);
//get values and assign it to variables
String yourData = sharedPref.getString("keyName", "defaultValue");
//to get retrive int value
int intValue = sharedPref.getInt("KeyName", 1);

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

Get Strings from ArrayList and save in Shared Preferences

I have an ArrayList that can contain 1 to 15 strings. Those strings need to be saved in my shared preferences, now I know how to iterate trough the array to get the strings. What I don't know, is there a clean way to dynamically add the strings to my shared preferences file? I could do this on a sluggish way by creating 15 strings and using an if statement to fill the shared preference, but I would like to know if there is a better way.
Thank you.
If its about naming, you can use something like this:
public static final String mPrefix = "mArray";
SharedPreferences prefs;
prefs = this.getSharedPreferences("PREF", 0);
prefsEditor = appSharedPrefs.edit();
//mAL is your ArrayList
for(int i=0; i<mAl.size(); i++){
prefsEditor.putString(mPrefix + "-" + i, mAl.get(i));
}
prefsEditor.commit();
You can use the putStringSet method available in SharedPreferences.Editor to store string arrays. For example:
String[] array = new String[]{"this", "is", "a", "string", "array"};
SharedPreferences.Editor edit = sharedPrefs.edit();
edit.putStringSet("myKey", new HashSet<String>(Arrays.asList(array)));
edit.commit();
Or if your API is below 11 then you may convert your string array into a single string and save it just like an ordinary string. For example:
edit.putString("myKey", TextUtils.join(",", array));
and later use the following to rebuild your array from string:
array = TextUtils.split(sharedPrefs.getString("myKey", null), ",");
Mainly to edit the shared prefernces data you need to take the Editor Object from it so you could edit it freely so to put data in it:
SharedPrefernces preferences = mContext.getSharedPreferences(MODE_PRIVATE);
Editor prefEditor = preferences.edit();
prefEditor.putString("this is a key object","this is value of the key");
You can also put inside different kinds of object for example : boolean , int , float , double and etc....
Just look up the editor class in android developers website...
In order to read the data from the sharedPrefrences it is even more simplier
SharedPrefrences pref = mContext.getSharedPreferences(MODE_PRIVATE);
pref.getString("the key of the value");

Categories

Resources