Save ArrayList to SharedPreferences

2018-12-31 00:07发布

I have an ArrayList with custom objects. Each custom object contains a variety of strings and numbers. I need the array to stick around even if the user leaves the activity and then wants to come back at a later time, however I don't need the array available after the application has been closed completely. I save a lot of other objects this way by using the SharedPreferences but I can't figure out how to save my entire array this way. Is this possible? Maybe SharedPreferences isn't the way to go about this? Is there a simpler method?

30条回答
梦寄多情
2楼-- · 2018-12-31 01:10

Also with Kotlin:

fun SharedPreferences.Editor.putIntegerArrayList(key: String, list: ArrayList<Int>?): SharedPreferences.Editor {
    putString(key, list?.joinToString(",") ?: "")
    return this
}

fun SharedPreferences.getIntegerArrayList(key: String, defValue: ArrayList<Int>?): ArrayList<Int>? {
    val value = getString(key, null)
    if (value.isNullOrBlank())
        return defValue
    return value.split(",").map { it.toInt() }.toArrayList()
}
查看更多
十年一品温如言
3楼-- · 2018-12-31 01:11

Using this object --> TinyDB--Android-Shared-Preferences-Turbo its very simple.

TinyDB tinydb = new TinyDB(context);

to put

tinydb.putList("MyUsers", mUsersArray);

to get

tinydb.getList("MyUsers");
查看更多
余生无你
4楼-- · 2018-12-31 01:11

Android SharedPreferances allow you to save primitive types (Boolean, Float, Int, Long, String and StringSet which available since API11) in memory as an xml file.

The key idea of any solution would be to convert the data to one of those primitive types.

I personally love to convert the my list to json format and then save it as a String in a SharedPreferences value.

In order to use my solution you'll have to add Google Gson lib.

In gradle just add the following dependency (please use google's latest version):

compile 'com.google.code.gson:gson:2.6.2'

Save data (where HttpParam is your object):

List<HttpParam> httpParamList = "**get your list**"
String httpParamJSONList = new Gson().toJson(httpParamList);

SharedPreferences prefs = getSharedPreferences(**"your_prefes_key"**, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(**"your_prefes_key"**, httpParamJSONList);

editor.apply();

Retrieve Data (where HttpParam is your object):

SharedPreferences prefs = getSharedPreferences(**"your_prefes_key"**, Context.MODE_PRIVATE);
String httpParamJSONList = prefs.getString(**"your_prefes_key"**, ""); 

List<HttpParam> httpParamList =  
new Gson().fromJson(httpParamJSONList, new TypeToken<List<HttpParam>>() {
            }.getType());
查看更多
明月照影归
5楼-- · 2018-12-31 01:12

Why don't you stick your arraylist on an Application class? It only get's destroyed when the app is really killed, so, it will stick around for as long as the app is available.

查看更多
十年一品温如言
6楼-- · 2018-12-31 01:12

Use this custom class:

public class SharedPreferencesUtil {

    public static void pushStringList(SharedPreferences sharedPref, 
                                      List<String> list, String uniqueListName) {

        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt(uniqueListName + "_size", list.size());

        for (int i = 0; i < list.size(); i++) {
            editor.remove(uniqueListName + i);
            editor.putString(uniqueListName + i, list.get(i));
        }
        editor.apply();
    }

    public static List<String> pullStringList(SharedPreferences sharedPref, 
                                              String uniqueListName) {

        List<String> result = new ArrayList<>();
        int size = sharedPref.getInt(uniqueListName + "_size", 0);

        for (int i = 0; i < size; i++) {
            result.add(sharedPref.getString(uniqueListName + i, null));
        }
        return result;
    }
}

How to use:

SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferencesUtil.pushStringList(sharedPref, list, getString(R.string.list_name));
List<String> list = SharedPreferencesUtil.pullStringList(sharedPref, getString(R.string.list_name));
查看更多
心情的温度
7楼-- · 2018-12-31 01:12

I used the same manner of saving and retrieving a String but here with arrayList I've used HashSet as a mediator

To save arrayList to SharedPreferences we use HashSet:

1- we create SharedPreferences variable (in place where the change happens to the array)

2 - we convert the arrayList to HashSet

3 - then we put the stringSet and apply

4 - you getStringSet within HashSet and recreate ArrayList to set the HashSet.

public class MainActivity extends AppCompatActivity { ArrayList arrayList = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    SharedPreferences prefs = this.getSharedPreferences("com.example.nec.myapplication", Context.MODE_PRIVATE);

    HashSet<String> set = new HashSet(arrayList);
    prefs.edit().putStringSet("names", set).apply();


    set = (HashSet<String>) prefs.getStringSet("names", null);
    arrayList = new ArrayList(set);

    Log.i("array list", arrayList.toString());
}
查看更多
登录 后发表回答