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.
Related
I have a list of classes that i would like to store in an Array or any data structure that would suite my problem. The array should be available across all the package and each element of the classes should be accessible from within the array. Its an Android app.
In Kotlin:
val class1 = Class1()
val class2 = Class2()
val list = ArrayList<Any>()
list.add(class1)
list.add(class2)
Any means you can store any type of object in it. Kotlin SmartCast allows you to check from ArrayList as well
In Java:
Class1 class1 = new Class1()
Class2 class2 = new Class2()
ArrayList list = new ArrayList<Object>()
list.add(class1)
list.add(class2)
You can store ArrayList in SharedPreferences and can use it in the whole application.
Here is sample code (You can optimize it)
public void saveArrayList(ArrayList<Object> list, String key){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
editor.putString(key, json);
editor.apply(); // This line is IMPORTANT !!!
}
public ArrayList<Object> getArrayList(String key){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
Gson gson = new Gson();
String json = prefs.getString(key, null);
Type type = new TypeToken<ArrayList<Object>>() {}.getType();
return gson.fromJson(json, type);
}
Here you fetch the object from ArrayList:
ArrayList list = getArrayList("some key");
for (int counter = 0; counter < list.size(); counter++) {
if(list[counter] instance of class1) {
// you have class1 object
}
if(list[counter] instance of class2){
// you have class2 object
}
}
if you don't need to persist the list, i think it will be better to use a singelton that contains a class list
I get JSON from a service, i save it in preference, and when user needs to check session or fetch data, he uses this method getProfileObject(), and it returns ArrayList in return.
This is my method that is responsible to get Json from preference and generate ArrayList by using Gson
SharedPreferences sharedPreferences=ApplicationContext.getAppContext().getSharedPreferences(USER_DATA_PREFERENCE, ApplicationContext.MODE_PRIVATE);
profileObject= sharedPreferences.getString(PROFILE_OBJECT, "");
if(!profileObject.isEmpty()) {
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
this.dataList = Arrays.asList(gson.fromJson(profileObject, Profile.class));
return dataList;
}
Now i want to avoid this Gson step each time, I want to store arrayList is shared preference, Is it possible to store java array list in shared preference.
Try using View Model class which will save it globally through out the activity life cycle.
hope this helps :
https://developer.android.com/topic/libraries/architecture/viewmodel#implement
public static void setArrayListPreference(Context context, ArrayList<String> list, String key){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
editor.putString(key, json);
editor.apply();
}
public static ArrayList<String> getArrayListPreference(Context context, String key){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
Gson gson = new Gson();
String json = prefs.getString(key, null);
Type type = new TypeToken<ArrayList<String>>() {}.getType();
return gson.fromJson(json, type);
}
Try this way..
Store Array list as serializable object like below ..
editor.putString("key", ObjectSerializer.serialize(currentTasks));// define arrayList
retrive the value.
currentTasks=(ArrayList<task>)ObjectSerializer.deserialize(prefs.getString(TASKS, ObjectSerializer.serialize(new ArrayList<task>())));
Gson dataJson = new Gson();
String userObject = dataJson.toJson(response.body());
after that it store sharedpreference userObject and get data.
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;
}
}
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());
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