0

i have async task where i am getting data from server in JSONArray format. I want to save that data in shared preferences and display it in list view. i am using adapter. I have tried but not getting anything

   JSONArray arr = new JSONArray(strServerResponse);
   JSONObject jsonObj = arr.getJSONObject(0);
   for (int i = 0; i < arr.length(); i++) {
       pojo = new Pojo();
       JSONObject jobj2 = arr.getJSONObject(i);
       String tipoftheday = jobj2.optString("tipsoftheday");
       ArrayList<String> tii = new ArrayList<String>();
       tii.add(tipoftheday);
   }

this tip of the day contains multiple data which i want to save in shared preferences and then show in list view. pojo is a class where i have defined setters and getters.

  ArrayList<Pojo> tips;
  tips = new ArrayList<Pojo>();
  pojo.setTip(mydatafromsharedprefernces);
  tips.add(pojo);
  tipsAdapter = new TipsAdapter(TipsActivity.this, tips);
  listTips.setAdapter(tipsAdapter);

how to add the data in shared prefernces. can anyone please help me.

3 Answers3

3

We have method "putStringSet" in "SharedPreferences.Editor".

putStringSet(String key, Set<String> values)

You have to convert ArrayList<Pojo> to Set. But Pojo must be serializable.

Set<String> set = new HashSet<String>(list);

and use the above method.

Check the following link.

http://developer.android.com/reference/android/content/SharedPreferences.Editor.html

Emil
  • 2,786
  • 20
  • 24
0

you mentioned you get data in json.Store that json string in shared preference. decode it when you get back from shared preferences.

Kirtan
  • 1,782
  • 1
  • 13
  • 35
0

Hope you know how to declare object of sharedPreference and how to use Editor object.

convert your arraylist to List<>

List<String> listTemp=tii ;

Add whole list in sharedPreference :

editor.putStringSet("key", listTemp);
editor.commit();

Retrieve list :

Set<String> set = editor.getStringSet("key", null);
Ravi
  • 34,851
  • 21
  • 122
  • 183
  • getting error Wrong 2nd argument type. Found: 'java.util.List', required: 'java.util.Set –  Sep 14 '15 at 09:08
  • List listTemp=tii ; Set temp = new HashSet(listTemp); SharedPreferences.Editor editor = getSharedPreferences( "MyPref",MODE_PRIVATE).edit(); editor.putStringSet("tipoftheday", temp); editor.commit(); now how can i set the value in pojo class –  Sep 14 '15 at 09:14
  • i have used pojo.setTip(set.toString()); but i am getting only onevalue –  Sep 14 '15 at 09:28