how save sharedpreferences in array - android

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

Related

How to convert a Textview array list into a hashset?

Hey stackoverflow community,
i want to send an Arraylist of Textviews through shared Preferences to another Activity, so i tried to convert my list into a HashSet.
This is not accepted:
public List<TextView> FavDishes = new ArrayList<TextView>();
.
.
.
FavDishes = new ArrayList<>();
FavDishes.add(eingabe);
**Set<String> taskSet = new HashSet<String>(FavDishes);**
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putStringSet("Data", taskSet)
.apply();
It tells me: "cannot resolve constructor HashSet on android widget Textview"
How would you solve this Problem?
Thanks for your time.
Iterate over the FavDishes array to get the TextView values as string and store them to an array, then pass that array to your taskset instead of FavDishes.
Code will be something like:
List<TextView> FavDishes = new ArrayList<TextView>();
FavDishes.add(fav1TV);
FavDishes.add(fav2TV);
FavDishes.add(fav3TV);
ArrayList<String> FavDishesString = new ArrayList<String>();
for (TextView FavDish : FavDishes ){
FavDishesString.add(FavDish.getText().toString());
}
Set<String> taskSet = new HashSet<String>(FavDishesString);
Helpful link to ways to iterate arrayList:
https://crunchify.com/how-to-iterate-through-java-list-4-way-to-iterate-through-loop/

Adding an item to arralist which is already saved in shared preferences in android

I am having an array list which is already stored in shared preferences.I want to add another item in array list.
Whenever i am trying to add an item in array list it is removing all the previous data stored in arraylist
How can i add item without removing the previous data in shared preferences
ArrayList<String> cartArrayListID,cartArrayListName,cartArrayListPrice,cartArrayListImage;
String cartID,cartName,cartPrice,cartImage;
cartArrayListID=new ArrayList<>();
cartArrayListName=new ArrayList<>();
cartArrayListPrice=new ArrayList<>();
cartArrayListImage=new ArrayList<>();
cartArrayListID.add(cartID);
cartArrayListName.add(cartName);
cartArrayListPrice.add(cartPrice);
cartArrayListImage.add(cartImage);
SharedPreferences sprefCart=getSharedPreferences("CARTINFO", Context.MODE_PRIVATE);
SharedPreferences.Editor editorCart=sprefCart.edit();
Gson gson = new Gson();
String id_=gson.toJson(cartArrayListID);
String name_=gson.toJson(cartArrayListName);
String price_=gson.toJson(cartArrayListPrice);
String image_=gson.toJson(cartArrayListImage);
editorCart.putString("ID", id_);
editorCart.putString("NAME", name_);
editorCart.putString("PRICE", price_);
editorCart.putString("IMAGE", image_);
editorCart.apply();
Toast.makeText(ProductActivity.this, "Added to cart", Toast.LENGTH_SHORT).show();
as I see in your code, you create a whole new ArrayLists cartArrayListID, cartArrayListName , ..etc everytime, and then you put the new value into it, after that you save it in SharedPreferences which in turn will replace the old one saved in it with your new one, so you have to:
get the corresponding ArrayList from Shared preferences at first.(for ex. cartArrayListName)
save it in a new array called cartArrayListID.
put the new values in this new array.
save it back in SharedPreferences.
You cannot get an ArrayList from SharedPreferences.
You can get a Set using getStringSet. Notice that the jdoc states that
Note that you must not modify the set instance returned by this call.
so do something like:
Set<String> mySet = new HashSet(yourPrefDataCollection);
mySet.add("some string");
sp.edit().putStringSet("your set key", mySet).commit();
Use GSON to get ArrayList from the String.
Add some items.
Try this example to save ArrayList to String, so you can store to SharedPreferences.
If your ArrayList has some special type (not String), use this construction:
ArrayList<Foo> list = new Gson().fromJson(
gsonString, new TypeToken<List<Foo>>(){}.getType());
The best way to accomplish this is by storing your array as a String in JSON format. You have to create a simple POJO to store your array and the rest is simple. See example below;
public void saveArray(List<String> yourArray) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("YOUR_ARRAY_KEY", new Gson().toJson(new ArrayListHolder(yourArray)));
editor.apply();
}
public List<String> getArray() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String arrayJson = sharedPreferences.getString("YOUR_ARRAY_KEY", null);
if (arrayJson != null) {
return new Gson().fromJson(arrayJson, ArrayListHolder.class).getYourArray();
}
return null;
}
private class ArrayListHolder {
private List<String> yourArray;
public ArrayListHolder(List<String> yourArray) {
this.yourArray = yourArray;
}
public List<String> getYourArray() {
return yourArray;
}
public void setYourArray(List<String> yourArray) {
this.yourArray = yourArray;
}
}

How to get each value from set after storing set in sharedpreference

I am using this code for string array of string values in shared preferences.
SharedPreferences preferences = context.getSharedPreferences(
"browser_opened_urls", 0);
Set<String> urls = new HashSet<String>();
for (int i = 0; i < Browser.mainWebViewFlipper.getChildCount(); i++) {
WebView webview = (WebView) Browser.mainWebViewFlipper
.getChildAt(i);
urls.add(webview.getUrl());
}
preferences.edit().putStringSet("URLs", urls).commit();
But i am not getting how to get the values when retrieving set from shared preferences. Can anyone help ?
This is my code when i am getting set.
SharedPreferences preferences = getSharedPreferences("browser_opened_urls", 0);
Set<String> urls = preferences.getStringSet("URLs", null);
Now can anyone tell me how to get each stored value from "urls" ?
Ok i found answer myself.
SharedPreferences preferences = getSharedPreferences("browser_opened_urls", 0);
Set<String> urls = preferences.getStringSet("URLs", null);
if (urls != null) {
Iterator<String> iterator = urls.iterator();
while (iterator.hasNext()) {
String url = iterator.next();
}
Use getString method to retrieve the data from sharedPreferences
As mentioned in the android api reference.
Use method:-
getStringSet(String key, Set<String> defValues)
The solution to your question is SharedPreferences prefs=preferences.getStringSet(String URLs, Set<String> urls);
This is assuming you want to store in a new object for retrieving the old set

How to keep some static data for future use in a spinner?

When the app starts, I got some static data (array) from the server, and I need to use this data for a spinner, on different activities. So this data should be available from different activities at different times to create a spinner.
How can I make this? How can I generate a spinner in code (spinner data is key = value)?
What type of data contains that array? Maybe you can use SharedPreferences to save it.
You can read about generating spinner here. CountryAdapter class is example of making spinner adapter which displays items in spinner drop down list.
EDIT:
Put your data into Hashtable and create 2 methods to save and read your data from SharedPreferences:
public boolean saveData( Hashtable<String, String> myData) {
Editor editor = getApplicationContext().getSharedPreferences("myData", Context.MODE_PRIVATE).edit();
for (String key : myData.values()) {
editor.putString(key, myData.get(key));
}
return editor.commit();
}
public Hashtable<String, String> restoreData() {
Hashtable<String, String> myData = new Hashtable<String, String>();
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("myData", Context.MODE_PRIVATE);
int size = sharedPreferences.getInt("size", 0);
for(int i =0; i < size; i++){
myData.put(sharedPreferences.getString("key"+i, "key+1"), sharedPreferences.getString("value"+i, "value+1"));
}
return myData;
}

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.

Categories

Resources