kakajan
kakajan

Reputation: 2697

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?

Upvotes: 45

Views: 91210

Answers (11)

Surajkaran Meghwanshi
Surajkaran Meghwanshi

Reputation: 676

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

Upvotes: 0

ar-g
ar-g

Reputation: 3495

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

Upvotes: 64

Peterstev Uremgba
Peterstev Uremgba

Reputation: 729

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)

Upvotes: 0

rafaelasguerra
rafaelasguerra

Reputation: 2555

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

Upvotes: 23

rahimpourDeveloper
rahimpourDeveloper

Reputation: 41

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!

Upvotes: 3

Shailendra Madda
Shailendra Madda

Reputation: 21531

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

Upvotes: 5

Walter Palladino
Walter Palladino

Reputation: 479

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.

Upvotes: 2

taran mahal
taran mahal

Reputation: 1088

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

Upvotes: 8

waqaslam
waqaslam

Reputation: 68177

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.

Upvotes: 1

Dario
Dario

Reputation: 2073

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

Upvotes: 1

MDMalik
MDMalik

Reputation: 4001

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/

Upvotes: 3

Related Questions