如何将List <Object>保存到SharedPreferences?

kak*_*jan 27 java android sharedpreferences

我有一个产品列表,我从webservice检索,当应用程序第一次打开时,应用程序从webservice获取产品列表.我想将此列表保存到共享首选项.

    List<Product> medicineList = new ArrayList<Product>();
Run Code Online (Sandbox Code Playgroud)

产品类是:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我如何保存此列表不是每次都从webservice请求?

ar-*_*r-g 30

它只能使用原始类型,因为首选项保留在内存中.但你可以使用的是将你的类型用Gson序列化为json并将字符串放入首选项:

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();
}
Run Code Online (Sandbox Code Playgroud)

  • 要从序列化源中检索List,请执行以下操作:`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); }` (4认同)
  • 在用GSON存储后,你有代码获取List吗? (2认同)

rgu*_*rra 18

您可以使用GSON转换对象 - > JSON(.toJSON)和JSON - >对象(.fromJSON).

  • 您想要定义标签(例如):

    private static final String PREFS_TAG = "SharedPrefs";
    private static final String PRODUCT_TAG = "MyProduct";
    
    Run Code Online (Sandbox Code Playgroud)
  • 获取这些标记的sharedPreference

    private List<Product> getDataFromSharedPreferences(){
        Gson gson = new Gson();
        List<Product> productFromShared = new ArrayList<>();
        SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(PREFS_TAG, Context.MODE_PRIVATE);
        String jsonPreferences = sharedPref.getString(PRODUCT_TAG, "");    
    
        Type type = new TypeToken<List<Product>>() {}.getType();
        productFromShared = gson.fromJson(jsonPreferences, type);
    
        return preferences;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 设置您的sharedPreferences

    private void setDataFromSharedPreferences(Product curProduct){
        Gson gson = new Gson();
        String jsonCurProduct = gson.toJson(curProduct);
    
        SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(PREFS_TAG, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
    
        editor.putString(PRODUCT_TAG, jsonCurProduct);
        editor.commit();
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 如果要保存一系列产品.你做这个:

    private void addInJSONArray(Product productToAdd){
    
        Gson gson = new Gson();
        SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(PREFS_TAG, Context.MODE_PRIVATE);
    
        String jsonSaved = sharedPref.getString(PRODUCT_TAG, "");
        String jsonNewproductToAdd = gson.toJson(productToAdd);
    
        JSONArray jsonArrayProduct= new JSONArray();
    
        try {
            if(jsonSaved.length()!=0){
                jsonArrayProduct = new JSONArray(jsonSaved);
            }
            jsonArrayProduct.put(new JSONObject(jsonNewproductToAdd));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    
        //SAVE NEW ARRAY
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putString(PRODUCT_TAG, jsonArrayProduct);
        editor.commit();
    }
    
    Run Code Online (Sandbox Code Playgroud)

  • 从 JSONArray 检索 Products 数组的代码是什么? (2认同)
  • 您不能像尝试使用此行那样将json直接放入SharedPreference中:`editor.putString(PRODUCT_TAG,jsonArrayProduct);`您必须首先将其转换为字符串(可能在代码中包含Gson对象)。例如:gson.toJson(jsonArrayProduct) (2认同)

小智 5

SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
Run Code Online (Sandbox Code Playgroud)

为了保存

Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(myObject);
prefsEditor.putString("MyObject", json);
prefsEditor.commit();
Run Code Online (Sandbox Code Playgroud)

为了得到

Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);
Run Code Online (Sandbox Code Playgroud)


Shy*_*dda 5

As said in accepted answer we can save list of objects like:

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

    public void set(String key, String value) {
        if (setSharedPreferences != null) {
            SharedPreferences.Editor prefsEditor = setSharedPreferences.edit();
            prefsEditor.putString(key, value);
            prefsEditor.commit();
        }
    }
Run Code Online (Sandbox Code Playgroud)

Get it by using:

public List<Company> getCompaniesList(String key) {
    if (setSharedPreferences != null) {

        Gson gson = new Gson();
        List<Company> companyList;

        String string = setSharedPreferences.getString(key, null);
        Type type = new TypeToken<List<Company>>() {
        }.getType();
        companyList = gson.fromJson(string, type);
        return companyList;
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)