0

I am working on an appengine connected android project. One of my endpoint methods returns a collection

return CollectionResponse.<MyData> builder().setItems(result).build();

When the data reaches android, I want to persist the data to SharedPreferences. This is a two steps process:

  1. Persist the json representing the response to sharedPreferences
  2. Unmarshall the json to CollectionResponseMyData or at the very least List<MyData>

Has anyone ever done this and don't mind sharing how?

To clarify, if needed, step 1 occurs when the data arrives. step 2 occurs at some later time when the data is needed.

Tom
  • 17,103
  • 8
  • 67
  • 75
learner
  • 11,490
  • 26
  • 97
  • 169

1 Answers1

0

Your data is a json so you can use gson to convert to string and back to json. You need that because you can't save json format on SharedPreference.

public boolean saveJson(List<MyData> myData){
    Gson gson = new Gson();
    String json = gson.toJson(myData);
    return saveMyData(json);
}

public List<MyData> getJson() {
    Type listOfObjects = new TypeToken<List<MyData>>(){}.getType();
    String json = restoreMyData();

    Gson gson = new Gson();
    List<MyData>  myListData = gson.fromJson(json, listOfObjects);
    return myListData;
}
public boolean saveMyData(String data) {
    SharedPreferences settings = context.getSharedPreferences("PrefName", 0);
    SharedPreferences.Editor editor = settings.edit();

    editor.putString("MyKey", data);
    return editor.commit();
}

public String restoreMyData() {
    SharedPreferences settings = context.getSharedPreferences("PrefName", 0);
    String data = settings.getString("MyKey", "default value, you can put null here");
    return data;
}
Scoup
  • 1,323
  • 8
  • 11