45

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?

kakajan
  • 2,614
  • 2
  • 22
  • 39

11 Answers11

62

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

 public List<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);
     }
}
Alireza Noorali
  • 3,129
  • 2
  • 33
  • 80
ar-g
  • 3,417
  • 2
  • 28
  • 39
  • hey i know this is really late but why are you using static variables and methods? – albert kim Feb 03 '16 at 01:32
  • @albertkim I believe this is so because he doesn't need new instances of SharedPreferences each time he needs it. He kept a variable tucked in somewhere for later use. – Neon Warge Jan 05 '17 at 05:48
  • 3
    And do you have the code to get the List after storing it with GSON? – Ali Obeid Nov 09 '17 at 16:48
  • 5
    To retrieve the List from the serialized source do that : `List arrayItems; String serializedObject = sharedPreferences.getString(KEY_PREFS, null); if (serializedObject != null){ Gson gson = new Gson(); Type type = new TypeToken>(){}.getType(); arrayItems = gson.fromJson(serializedObject, type); }` – StevenTB Jul 26 '18 at 12:45
  • how are you using `context.getShar...` when your instance is static? I am guessing that `context` is also static, but is it wise to use context as static? – ansh sachdeva Jan 23 '20 at 11:34
23

You can use GSON to convert Object -> JSON(.toJSON) and JSON -> Object(.fromJSON).

  • Define your Tags with you want (for example):

    private static final String PREFS_TAG = "SharedPrefs";
    private static final String PRODUCT_TAG = "MyProduct";
    
  • Get your sharedPreference to these tag's

    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;
    }
    
  • Set your 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();
    }
    
  • If you want to save an array of Products, do this:

    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();
    }
    
Tincho825
  • 829
  • 1
  • 13
  • 15
rafaelasguerra
  • 2,685
  • 5
  • 24
  • 56
  • 2
    What is the code to retrieve the array of Products from the JSONArray ? – Adina Marin Sep 04 '15 at 11:40
  • 2
    You can't put json directly into SharedPreference as you tried doing with this line: `editor.putString(PRODUCT_TAG, jsonArrayProduct);` You have to convert it first to string (possibly with the Gson object in your code). For example: `gson.toJson(jsonArrayProduct)` – O'Kamiye Apr 02 '17 at 00:06
  • I am getting Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $ when getting the objects – Martin De Simone Mar 09 '18 at 01:00
8
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);

For save

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

For get

Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);
taran mahal
  • 1,068
  • 12
  • 11
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();
        }
    }

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;
}
Shailendra Madda
  • 20,649
  • 15
  • 100
  • 138
3

You currently have two options
a) Use SharedPreferences
b) Use SQLite and save values in that.

How to perform
a) SharedPreferences
First store your List as a Set, and then convert it back to a List when you read from SharedPreferences.

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

Then when you read it:

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

b) SQLite A good tutorial: http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/

MDMalik
  • 3,951
  • 2
  • 25
  • 39
3

The best solution for me and I think you :

private static SharedPreferences sharedPreferences = context.getSharedPreferences(STORE_FILE_NAME, Context.MODE_PRIVATE);
private  SharedPreferences.Editor editor = sharedPreferences.edit();
List<your object> list = new ArrayList<>();

For save:

editor.edit().putString("your key name", new Gson().toJson(list)).apply();

For get:

list = new Gson().fromJson(sharedPreferences.getString("your key name", null), new TypeToken<List<your object class name>>(){}.getType());

enjoy it!

2

All the answer related to JSON are Ok but remember Java allows you to serialize any object if you implement the java.io.Serializable interface. This way you can save it to preferences as a serialized object too. Here is an example for storing as Preferences: https://gist.github.com/walterpalladino/4f5509cbc8fc3ecf1497f05e37675111 I hope this could help you as an option.

Walter Palladino
  • 479
  • 1
  • 3
  • 8
1

In SharedPreferences you can store only primitives.

As one possible approach is that you can use GSON and store values into preferences in JSON.

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

yourPrefereces.putString("listOfProducts", json);
yourPrefereces.commit();
Dario
  • 2,053
  • 21
  • 31
1

You may do it using Gson as below:

  • Download List<Product> from webservice
  • Convert the List into Json String using new Gson().toJson(medicineList, new TypeToken<List<Product>>(){}.getType())
  • Save the converted string into SharePreferences as you do normally

In order to reconstruct your List, you need to revert the process using fromJson method available in Gson.

waqaslam
  • 67,549
  • 16
  • 165
  • 178
0

the perfect fucntion for getting generic lists in Kotlin

private fun <T : Serializable> getGenericList(
    sharedPreferences: SharedPreferences,
    key: String,
    clazz: KClass<T>
): List<T> {
    return sharedPreferences.let { prefs ->
        val data = prefs.getString(key, null)
        val type: Type = TypeToken.getParameterized(MutableList::class.java, clazz.java).type
        gson.fromJson(data, type) as MutableList<T>
    }
}

you can call this function

getGenericList.(sharedPrefObj, sharedpref_key, GenericClass::class)
0

We can save ArrayList into shared Preference using Set

Step 1 : Save into shared Preference

// bList is - ArrayList<String>()
putStringSet("reportedList", set)

Step 2 : retrieve data from shared Preference

val setReport = PrefManager(requireContext()).getStringSet("reportedList")
val bList = ArrayList<String>()
if (setR!= null ){
    setR?.toList().forEach {
        bList .add(it)
    }
 }