In shared preferences how to store string array in android application - android

In my application am using list view in base adapter.
when i click the item its id store in shared preferences string array format. how to save multiple item id in string array format
[1,2,5,6] like this

You can try using JSONArray as JSON is light-weight also, you can create a JSONArray and write it to SharedPreference as String.
To write,
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
JSONArray jsonArray = new JSONArray();
jsonArray.put(1);
jsonArray.put(2);
Editor editor = prefs.edit();
editor.putString("key", jsonArray.toString());
System.out.println(jsonArray.toString());
editor.commit();
To Read,
try {
JSONArray jsonArray2 = new JSONArray(prefs.getString("key", "[]"));
for (int i = 0; i < jsonArray2.length(); i++) {
Log.d("your JSON Array", jsonArray2.getInt(i)+"");
}
} catch (Exception e) {
e.printStackTrace();
}

If you are using API 11 then its possible by using putStringSet. Otherwise you may either convert your string array into a single string as mentioned by #hotverispicy or use SQLite database

you can save it as string by ,(comma) seperator and while fetching just use split()
string toPut="";
toPut += "listItem,";
set toPut in your SharePreference and commit()
To get the same in array: get prefString from SharePreference
String[] fetchArray= prefString.split(",");

Related

How to store Integer Hashset in SharedPreference?

It says wrong 2nd argument type required set String.
Set<Integer> hs = pref.getStringSet("set", new HashSet<Integer>());
hs.add(String.valueOf(hs.size()+1));
SharedPreferences.Editor edit = pref.edit();
edit.putStringSet("set", hs);
edit.commit();
You can do the conversion and store it in SharedPreferences like this,
SharedPreferences preferences = context.getSharedPreferences("preferences", Context.MODE_PRIVATE);
Set<Integer> integerHashSet = new HashSet<>();
integerHashSet.add(1);
integerHashSet.add(2);
//convert String HashSet to Integer HashSet
Set<String> stringHashSet = new HashSet<>();
for (Integer i : integerHashSet) {
stringHashSet.add(String.valueOf(i));
}
preferences.edit().putStringSet("set", stringHashSet).commit();
Set<String> stringSet = preferences.getStringSet("set", new HashSet<String>());
Set<Integer> integerSet = new HashSet<>();
//Convert it back
for (String str : stringSet) {
integerSet.add(Integer.parseInt(str));
}
//now user integerSet
Use Gson
implementation 'com.google.code.gson:gson:2.8.5'
Gson helps to convert custom object to string & string to custom object.
So you can convert set to string save to shared pref. And later get string from shared pref and convert to set.
To save
Set<Integer> mySet = new HashSet<>();
String json = new Gson().toJson(mySet);
//Save json to shared pref
Then to retrieve
//get json from shared preference saved earlier
Set<Integer> mySet2 = new Gson().fromJson(json, new TypeToken<Set<Integer>>() {
}.getType());
It says wrong 2nd argument type required set String.
It's because you're incorrectly using the getStringSet with the following code:
Set<Integer> hs = pref.getStringSet("set", new HashSet<Integer>());
it should be like this:
Set<String> hs = pref.getStringSet("set", new HashSet<String>());
You should recognize the method signature which is clearly telling that the method is giving you a string set with getStringSet.

How to save Arraylist of Objects from Fragment class into SharedPreferencess

I saw similar questions in stackoverflow ( LINK , LINK ) and other websites . They are doing everything from an Activity hence they didn't get problem.
I have an Activity and Fragment class. I am trying to save ArrayList of Object into shared preferences from a Fragment. Below is what i tried
SharedPreferences prefs = getActivity().getSharedPreferences("SHARED_PREFS_FILE", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
try {
editor.putString("taggedFriends",ObjectSerializer.serialize(taggableFriends));
} catch (IOException e) {
e.printStackTrace();
Its showing error at ObjectSerializer
**Cannot resolve symbom 'ObjectSerializer'**
I tried
getActivity.ObjectSerializer.serialize(..);
But error didn't go. Help me what can i do now.
Thankyou for spending time for me.
Try this:
Last edit:
In this case:
static class YourObject
{
private String _name;
public YourObject(String name)
{
this._name = name;
}
}
YourObject yourObject = new YourObject(myName);
ArrayList<YourObject> foo = new ArrayList<YourObject>();
foo.add(yourObject);
convert an ArrayList to JSONArray:
JSONArray mJSONArray = new JSONArray(foo);
Then save the JSONArray:
SharedPreferences.Editor editor = prefs.edit();
editor.putString("yourStringName", mJSONArray.toString());
String to JSONArray:
SharedPreferences prefs = getSharedPreferences("SHARED_PREFS_FILE", Context.MODE_PRIVATE);
String myJSONArrayString = prefs.getString("yourStringName", "");
JSONArray jsonArray = new JSONArray(myJSONArrayString);
JSONArray to ArrayList:
ArrayList<String> list = new ArrayList<String>();
for (int i=0;i<jsonArray.length();i++){
list.add(jsonArray.get(i).toString());
}
I hope this solve your question.
First add Gson to your gradle:
compile 'com.google.code.gson:gson:2.2.4'
Convert your list to Json String like below:
List<String> foo = new ArrayList<String>();
foo.add("Item1");
foo.add("Item2");
foo.add("Item3");
String json = new Gson().toJson(foo );
And save it to shared pref like below:
SharedPreferences.Editor mEditor = mPrefs.edit();
mEditor.putString("yourKey", json);
And when you want to use read your saved json string from pref:
String json = mPrefs.getString("yourKey", "");
Convert your Json String to list of your objects like below. In example i used String.
ArrayList<String> foo = (ArrayList<String>) new Gson().fromJson(json,
new TypeToken<ArrayList<String>>() {
}.getType());

SharedPreferences, doubles and arrays in Android

I have a user to insert 10 numbers that will be stored in an array. From this number the average is calculated and stored in a double.
Now I want send the array and the double to another activity but I don't see any option when I type editor.put.
How can I do that?
public int[] number = new int[10];
public double avg;
...
SharedPreferences.Editor editor = myPrefs.edit();
editor.put...
editor.put...
editor.commit();
Thanks,
Marco
If you only need to pass these values to another Activity and not hold on to them for longer term use, just embed them as an extra in the Intent used to start the other Activity.
Just use your own String keys which are known to both Activity classes and call:
putExtra(YOUR_INT_ARRAY_KEY, yourIntArray)
putExtra(YOUR_DOUBLE_KEY, yourDoubleVal)
Maybe you can just use JSON if that isn't too much overhead for you.
See this example:
JSONArray jsonArray = new JSONArray();
for(int i = 0; i < number.length; i++) {
jsonArray.put(i, number[i]);
}
...
editor.put("YOUR_KEY", jsonArray.toString());
...
JSONArray array = new JSONArray(myPrefs.getString("YOUR_KEY", ""));
array.get(i);
...
Here the Link to the API. JSONObject may also be worth a look at:
JSONObject
JSONArray
I solved the problem in this way. It works well.
public int[] number = new int[10];
public double avg;
...
SharedPreferences.Editor editor = myPrefs.edit();
editor.putFloat(AVERAGE, avg);
StringBuilder intArrayToString = new StringBuilder();
for(int i=0; i<number.length; i++)
{
intArrayToString.append(number[i]).append(",");
}
editor.putString(INT_TO_STRING, intArrayToString.toString());
editor.commit();

Storing a String array in the SharedPreferences

I was wondering if it could be possible to save in the shared preferences an array of Strings, in a way that, every time we save a certain String, we store it in that array.
For example I have a list of locations with a certain ID that I want to mark as favorite.
The ideal situation would be, having an array and saving a certain location ID (let's call it Location1) in that array, so next time I want to mark a new location as favorite (let's call it Location2), I retrieve that array (which so far contains Location1) and add the ID of this new location I want to add (Location2).
Android has methods to store primitive objects, but not for arrays.
Any idea in order to do this, please?
This is doable: I was just blogging about it:
SAVE YOUR ARRAY
//String array[]
//SharedPreferences prefs
Editor edit = prefs.edit();
edit.putInt("array_size", array.length);
for(int i=0;i<array.length; i++)
edit.putString("array_" + i, array[i]);
edit.commit();
RETRIEVE YOUR ARRAY
int size = prefs.getInt("array_size", 0);
array = new String[size];
for(int i=0; i<size; i++)
prefs.getString("array_" + i, null);
Just wrote that so there might be typos.
You could make the array a JSON array and then store it like this:
SharedPreferences settings = getSharedPreferences("SETTINGS KEY", 0);
SharedPreferences.Editor editor = settings.edit();
JSONArray jArray = new JSONArray();
try {
jArray.put(id);
} catch (JSONException e) {
e.printStackTrace();
}
editor.putString("jArray", jArray.toString());
editor.commit();
You can then get the array like this:
SharedPreferences settings = getSharedPreferences("SETTINGS KEY", 0);
try {
JSONArray jArray = new JSONArray(settings.getString("jArray", ""));
} catch (JSONException e) {
e.printStackTrace();
}
Just an alternative solution that I have used in the past
Write methods to read and write a serialized array. This shouldn't be too difficult. Just flatten the array of strings into a single string that you store in the preferences. Another option would be to convert the array into an XML structure that you then store in the preferences, but that is probably overkill.

Removing Object from JSONArray

I have an application that gets an api key and account name from a webservice, I am storing this apikey and account name for further use(multiple accounts and apikeys).
because you can only store primitive types in the sharedPreferences I parse the JSONArray toString.
In another part of the application the user must be able to remove an account from his app.
So I retrieve the string and Parse it back to an JSONArray.
how do I remove an JSONObject from the array and save it so I can parse it back to an string and save it again?
You should convert it in arraylist and remove object and create jsonarray,,,
ArrayList<String> list = new ArrayList<String>();
//First Position remove
list.remove(0);
JSONArray jsArray = new JSONArray(list);
i use:
public static JSONArray RemoveJSONArray( JSONArray jarray,int pos) {
JSONArray Njarray=new JSONArray();
try{
for(int i=0;i<jarray.length();i++){
if(i!=pos)
Njarray.put(jarray.get(i));
}
}catch (Exception e){e.printStackTrace();}
return Njarray;
}

Categories

Resources