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");
Related
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).
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));
}
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.
I would like to know how I would be able to able achieve getting the strings from my shared preferences(I have already set up), then outputting it to a String array so that my Image Fetcher will be able to read it(It has to be an array for it to read).
In one activity I am setting the shared preferences:
case R.id.FavouriteWallpaper:
SharedPreferences prefs;
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = prefs.edit();
editor.putString("imgUrl", mImageUrl);
editor.commit();
}
return super.onOptionsItemSelected(item);
}
In another class I am getting the string from shared preferences:
SharedPreferences prefs;
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
prefs.getString("imgUrl", null); //Output imgUrl to String Array somehow
// I would like my image fetcher to read a string array that has been fetched from shared preferences.
mImageFetcher.loadImage(Fragment3.imgUrl[position
- mNumColumns], imageView);
return imageView;
}
You can not really save an array to SharedPrerences, but you can store all your urls in a string like CSV (comma separated values) and store it in sharePreferences. You can write a manager that will have 2 methods. One to transform your array to CSV and store and the second get the CSV and transform it to an array.
The second method is to save the data like a JSONArray to do this you also need to write a manager that will have 2 methods also, one to transform your array to JSONArray and store it in Shared Preferences, and the second to transform the jsonArray into your array.
you can get the strings using for loop
examole...
SharedPreferences prefs;
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = prefs.edit();
editor.putString("imgUrl", mImageUrl);
for(int i=0; i<arraylist.size(); i++)
{
editor.putString("imgUrl"+i, arraylist.get(i).toString());
}
editor.commit();
I am trying to save an int array into the shared preferences.
int myInts[]={1,2,3,4};
SharedPreferences prefs = getSharedPreferences(
"Settings", 0);
SharedPreferences.Editor editor = prefs
.edit();
editor.putInt("savedints", myInts);
Since the putInt method does not accept int arrays, I was wondering if anyone knew another way to do this. Thanks
Consider JSON.
JSON is well integrated into Android and you can serialize any complex type of java object. In your case the following code would be suited well.
// write
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
JSONArray arr = new JSONArray();
arr.put(12);
arr.put(-6);
prefs.edit().putString("key", arr.toString());
prefs.edit().commit();
// read
try {
arr = new JSONArray(prefs.getString("key", "[]"));
arr.getInt(1); // -6
} catch (JSONException e) {
e.printStackTrace();
}
you can add only primitive values to sharedpreference ......
refer this doc:
http://developer.android.com/reference/android/content/SharedPreferences.html
You can serialize an array to String using TextUtils.join(";", myInts) and the deserialize it back using something like TextUtils. SimpleStringSplitter or implement your own TextUtils.StringSplitter.
If your integers are unique, perhaps you can use putStringSet (see docs). Otherwise you have to resort to serializing / formatting your integer array as String, as suggested by other answers.