简体   繁体   中英

How to save data to sharedpreference in a flexible way

I save chosen items into shared preference, but as the user during runtime get to remove any of these items (from any position), and as I use the saved size (in the code below) to loop through the items, and here's the problem

Say I have 5 items ( item_1 - item_2 - item_3 - item_4 - item_5 )

if the user removed item_2 I update chosen_items_size to be 4 and I remove item_2 from the shared preference.

but when I load the items later I use the (size = which is 4 now), which as in the code below will miss item_5, how to fix this, any suggestions or better approach to achieve what I need?

    mSharedPreference = getSharedPreferences("chosen_items", MODE_PRIVATE);
    int size = mSharedPreference.getInt("chosen_items_size", 0);
    for(int i = 1; i <= size; i++) {

       mSharedPreference.getString("item_" + i, null);

    }

Knowing that I want to enable drag and drop items, which using the above approach will make it pretty hard (if possible in the first place) to accomplish, any better approach to save & retrieve data / items?

Thank you

If you have a small amount of strings you can store them in one delimited string in SharedPreferences like so . You could also associate some metadata with each item and delimit that too.

You could utilize a built in SQL lite database.
Is this data that must persist between sessions? if not store it locally with a class and static variables/arrays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM