0

I'm saving a list with json in SharedPreferences. This works just fine, but when I try to load it Android Studio tells me I can't

private List<AppInfo> apps;

apps = new ArrayList<AppInfo>();

// Storing in method
ArrayList<String> lollist = new ArrayList<>();
lollist = new ArrayList<>(Arrays.asList(String.valueOf(apps)));
setStringArrayPref(this, "urls", lollist);

// Loading which doesn't work
lollist = getStringArrayPref(this, "urls");
apps = (String[]) lollist.toArray();

The error I get is

Required: java.util.list <com.....AppInfo>
Found: java.lang.String[]

How may I do this?

Carl
  • 249
  • 2
  • 5
  • 13
  • I'm afraid an array of `String` will **never** be a list of `AppInfo` –  Jun 02 '15 at 15:57
  • Related: http://stackoverflow.com/questions/7145606/how-android-sharedpreferences-save-store-object –  Jun 02 '15 at 15:58
  • @RC What I'm doing is saving a list of all packagenames (installed apps) to SharedPreferences. This works fine with saving. Just not loading. I found serializing best, so I'm serializing with this: http://stackoverflow.com/questions/7361627/how-can-write-code-to-make-sharedpreferences-for-array-in-android/7361989#7361989 – Carl Jun 02 '15 at 16:00
  • If you're casting it into `String[]`, shouldn't `apps` be of type `String[]` as well? – Anindya Dutta Jun 02 '15 at 16:01
  • @Carl I think you misunderstood `String.valueOf`, you should read the "related" question –  Jun 02 '15 at 16:03

1 Answers1

0

You might wanna use Gson library for this. Which provides you easier one line options to convert a data structure to Json and vice versa.

Usage :

private Gson gson = new Gson();
private List<AppInfo> apps = new ArrayList<AppInfo>();

String jsonString = gson.toJson(apps); //You may store this string in your shared preference
Type type = new TypeToken<List<AppInfo>>() {}.getType();
apps = gson.fromJson(jsonString, type);

NOTE : You should Expose the variables in your Data model class to use Gson. Like this.

@Expose
private String name;
siriscac
  • 1,699
  • 12
  • 21