web-dev-qa-db-fra.com

Comment sauvegarder List <Object> en SharedPreferences?

J'ai une liste de produits, que je récupère de Webservice, lorsque l'application est ouverte pour la première fois, l'application obtient la liste des produits de Webservice. Je veux enregistrer cette liste dans les préférences partagées.

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

où la classe de produit est:

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;
    }
}

comment puis-je sauvegarder cette liste ne demandant pas de WebService à chaque fois?

24
kakajan

Il est uniquement possible d'utiliser des types primitifs car les préférences restent en mémoire. Mais ce que vous pouvez utiliser est de sérialiser vos types avec Gson dans json et de mettre chaîne dans les préférences:

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();
}
26
ar-g

Vous pouvez utiliser GSON pour convertir objet -> JSON (.toJSON) et JSON -> objet (.fromJSON).

  • Définissez vos balises avec votre envie (par exemple):

    private static final String PREFS_TAG = "SharedPrefs";
    private static final String PRODUCT_TAG = "MyProduct";
    
  • Obtenez votre référence partagée à ces balises

    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;
    }
    
  • Définissez vos préférences partagées 

    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();
    }
    
  • Si vous souhaitez enregistrer un tableau de produits. Tu fais cela:

    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();
    }
    
15
rguerra

Vous avez actuellement deux options
a) Utiliser SharedPreferences
b) Utilisez SQLite et enregistrez les valeurs dans cela.

Comment effectuer
a) Préférences partagées
Commencez par stocker votre liste en tant qu’ensemble, puis reconvertissez-la en liste lorsque vous lisez à partir de SharedPreferences. 

Listtasks = new ArrayList<String>();
Set<String> tasksSet = new HashSet<String>(Listtasks);
PreferenceManager.getDefaultSharedPreferences(context)
    .edit()
    .putStringSet("tasks_set", tasksSet)
    .commit();

Puis quand tu le lis:

Set<String> tasksSet = PreferenceManager.getDefaultSharedPreferences(context)
    .getStringSet("tasks_set", new HashSet<String>());
List<String> tasksList = new ArrayList<String>(tasksSet);

b) SQLite Un bon tutoriel: http://www.androidhive.info/2011/11/Android-sqlite-database-tutorial/

3
MDMalik
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);

Pour sauvegarder

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

Oublier

Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);
2
taran mahal

Toutes les réponses liées à JSON sont Ok mais n'oubliez pas que Java vous permet de sérialiser n'importe quel objet si vous implémentez l'interface Java.io.Serializable . Vous pouvez ainsi l'enregistrer dans les préférences en tant qu'objet sérialiséVoici un exemple de stockage en tant que préférences: https://Gist.github.com/walterpalladino/4f5509cbc8fc3ecf1497f05e37675111 J'espère que cela pourra vous aider en tant qu'option.

2
Walter Palladino

Comme indiqué dans la réponse acceptée, nous pouvons enregistrer une liste d'objets tels que:

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();
        }
    }

Obtenez-le en utilisant:

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;
}
1
Shylendra Madda

Dans SharedPreferences, vous ne pouvez stocker que des primitives.

Une approche possible consiste à utiliser GSON et à stocker des valeurs dans des préférences en JSON.

Gson gson = new Gson();
String json = gson.toJson(medicineList);

yourPrefereces.putString("listOfProducts", json);
yourPrefereces.commit();
1
Dario

Vous pouvez le faire en utilisant Gson comme ci-dessous:

  • Téléchargez List<Product> à partir du service Web
  • Convertissez la List en Json String en utilisant new Gson().toJson(medicineList, new TypeToken<List<Product>>(){}.getType())
  • Enregistrez la chaîne convertie dans SharePreferences comme vous le faites normalement

Pour reconstruire votre List, vous devez inverser le processus en utilisant la méthode fromJson disponible dans Gson.

0
waqaslam