0

Saving the data is done but I am not able to retrieve the data it showing

java.util.HashSet cannot be cast to java.lang.String

Here my code.(Save)

                   List<String> historyList = new ArrayList<>();
                   historyList.add(data.get(position).getProductName());
                   Set<String> set = new HashSet<>();
                   set.addAll(historyList);
                   preference.save("History", set);

(Retrieve)

  Log.d("History", "hhhhhhhhhhhhhhhhh"  +preference.readString("History",""));

Please help me to solve this issue.

Surendar D
  • 5,554
  • 4
  • 36
  • 38

4 Answers4

0

Since you are saving the Set you need to retrieve the Set instead to Stringand you can convert it to List again.

 Set<String> set = preference.getStringSet("History", null);
 List<String> historyList = new ArrayList<>();
 historyList.addAll(set);
Vignesh Sundaramoorthy
  • 1,827
  • 1
  • 25
  • 38
0

After you prepare ArrayList of all items, convert it to a comma separated String.

String itemsString = TextUtils.join(",", historyList);
preference.save("History", itemsString);

When you retrieve it, convert it back into an Array.

String [] itemsArray = preference.readString("History","").split(",");
Thafer Shahin
  • 814
  • 9
  • 10
0

Retrieve the values

Gson gson = new Gson();
String jsonText = Prefs.getString("key", null);
String[] text = gson.fromJson(jsonText, String[].class);  //EDIT: gso to gson

Set the values

Gson gson = new Gson();
List<String> historyList = new ArrayList<>();
historyList.addAll(data);
String jsonText = gson.toJson(historyList);
prefsEditor.putString("key", jsonText);
prefsEditor.commit();
Komal12
  • 3,340
  • 4
  • 16
  • 25
0

You can add your array list to preference by converting them to string.

First convert your array to string using Gson.

ArrayList<CustomObject> yourlist=new ArrayList<>();
public static final String MY_PREFS_NAME = "MyPrefsFile";

Fill your array

Gson gson=new Gson();
String myfav = gson.toJson(yourlist);

SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
 editor.putString("myfav", myfav);
 editor.commit();

Then read this string where you need this

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME,MODE_PRIVATE); 
String restoredText = prefs.getString("myfav", null);

Now get back your array list in following way:

Type type = new TypeToken<ArrayList<CustomObject>>() { }.getType();
       ArrayList<CustomObject> yourfinallist=new ArrayList<>();
       gson = new Gson();
       yourfinallist = gson.fromJson(myfav, type);
Yyy
  • 2,285
  • 16
  • 29