Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
98 views
in Technique[技术] by (71.8m points)

java - How to save List<Object> to SharedPreferences?

I have a list of products, which i retrieve from webservice, when app is opened for first time, app gets product list from webservice. I want to save this list to shared preferences.

    List<Product> medicineList = new ArrayList<Product>();

where Product class is:

public class Product {
    public final String productName;
    public final String price;
    public final String content;
    public final String imageUrl;

    public Product(String productName, String price, String content, String imageUrl) {
        this.productName = productName;
        this.price = price;
        this.content = content;
        this.imageUrl = imageUrl;
    }
}

how i can save this List not requesting from webservice each time?

question from:https://stackoverflow.com/questions/28107647/how-to-save-listobject-to-sharedpreferences

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It only possible to use primitive types because preference keep in memory. But what you can use is serialize your types with Gson into json and put string into preferences:

private static SharedPreferences sharedPreferences = context.getSharedPreferences(STORE_FILE_NAME, Context.MODE_PRIVATE);

private static SharedPreferences.Editor editor = sharedPreferences.edit();

public <T> void setList(String key, List<T> list) {
    Gson gson = new Gson();
    String json = gson.toJson(list);

    set(key, json);
}

public static void set(String key, String value) {
    editor.putString(key, value);
    editor.commit();
}


Extra Shot from below comment by @StevenTB

To Retrive

 publicList<YourModel> getList(){
    List<YourModel> arrayItems;
    String serializedObject = sharedPreferences.getString(KEY_PREFS, null); 
    if (serializedObject != null) {
         Gson gson = new Gson();
         Type type = new TypeToken<List<YourModel>>(){}.getType();
         arrayItems = gson.fromJson(serializedObject, type);
     }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...