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.
Related
I tried to do it with multiple Shared Preferences keys, but it goes quiet complicated.
I saw some said that it is possible with JSON, but have no idea how to do it.
My app has many items in ListView, and I want to save several values in each item.
You can imagine a contact management app.
When the Item(person name) is clicked, you can check the values like phone number, address, and picture. And of course, they can be edited, added and deleted.
Is it possible to save values in single KEY with JSON?
So that I can load the values for each item when it is clicked.
To be able to save multiple values inside a jsonObject you can do this
try {
JSONObject Contacts = new JSONObject();
Contacts.put("Name", "Saul Goodman");
Contacts.put("Address", "Ocean Drive");
Contacts.put("Phone", "13456");
Contacts.put("Contacts", Contacts);
} catch (JSONException e) {
e.printStackTrace();
}
So that will create a structure like this
"Contacts":{
"Name":"Saul Goodman",
"Address":"Ocean Drive",
"Phone":"123456"
}
};
To retrieve this values you should do this
JSONArray array = object.getJSONArray("Contacts");
for(int i = 0; i < array.length; i++) {
JSONObject object = (JSONObject) array.get(i);
String name = object.get("Name");
String address = object.get("Address");
String phone = object.get("Phone");
//you also can use object.getString(""); to get the strings
}
hope it helps
Happy coding !
how can I save a shared preference to an array, I tried a couple of things but I just can't do it, I want to save a specific key into the array and then put them in a textview and it just crash.
please help guys.
public String[] fetchAllPreference(){
SharedPreferences sharedPref = getSharedPreferences("DictionaryInfo",
Context.MODE_PRIVATE);
//here i want the code of making it into array come
return values;
}
public void loadPicture()
{
gallery.removeAllViews();
String[] array =fetchAllPreference();
for(int i=0;i<array.length;i++)
{
TextView iv = new TextView(this);
LinearLayout.LayoutParams layoutParams=new
LinearLayout.LayoutParams(100,100);
layoutParams.setMargins(10,10,0,0);
iv.setLayoutParams(layoutParams);
iv.setText(array[i].toString());
gallery.addView(iv);
}
}
I know it isnt the exact answer, but it is possible to save each element of the array with the index being the keyword or index assossiated with some string being the keyword.
i think what u want is to save values in sharedpreference to an array, in that case
SharedPreferences prefs = getSharedPreferences("myFavs", 0);
Map<String, String> m = (Map<String, String>) prefs.getAll();
a map can be coverted to a collection
(https://developer.android.com/reference/java/util/Map.html)
and collection can be converted to an array
(https://developer.android.com/reference/java/util/Collection.html)
pls read this, it seems similar
Getting shared preferences and displaying them in a listview
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();
i wish to, in one activity, put strings in the sharedpreferences, so then, in another activity, i get those strings, put them in a array and display them sequentially. I managed to do this, but i don`t have any idea how can i delete one specified string when asked. These strings will just be scattered on the shared preferences,and i dont know how to keep track of them. I can pass this unique int id to each element. I tried to use LinkedList, but i cannot pass this kind of structure as a shared preferences. I did not managed to make Gson work also. Please help.
Method that gets the string and put on shared preferences:
public void makefavorites(String[] a, String[] b, int id)
{
int idfinal = id%10;
idfinal = idfinal+1;
a[idfinal] = b[idfinal] +"\n" + "\n"+ a[idfinal];
SharedPreferences prefs = getSharedPreferences("Favorites", Activity.MODE_PRIVATE);
Editor edit = prefs.edit();
int temp = prefs.getInt("favorites_size", 0);
edit.putInt("favorites_size", temp+1);
edit.putString("array_" + prefs.getInt("favorites_size", 0), a[idfinal]);
edit.commit();
refreshfavorites();
}
Method that gets those strings, put on array and display it:
public void refreshfavorites()
{
SharedPreferences prefs = getSharedPreferences("Favorites", Activity.MODE_PRIVATE);
//GETS THE ARRAY SIZE
int size = prefs.getInt("favorites_size", 0);
String[] array = new String[size];
for(int i=0; i<size; i++){
array[i] = prefs.getString("array_" + i, null);
}
}
you have to use editor.remove method to delete specific value from arraylist..
public void removeArray(String[] list)()
{
SharedPreferences.Editor editor = mSharedPrefs.edit();
int size = list.length();
for (int i = 0; i < size; i++) {
editor.remove("favorites_size"+i);
}
editor.commit();
}
i hope its useful to you..
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(",");