1

Is it a good idea to store a list of String with too many items in Sharedpreferences? Does it hurt app performance?

I'm doing this to store:

public boolean saveArray(List<String> contacts) {
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(_context);
    SharedPreferences.Editor editor = sp.edit();
    editor.putInt("Status_size", contacts.size());
    for (int i = 0; i < contacts.size(); i++) {
        editor.remove("Status_" + i);
        editor.putString("Status_" + i, contacts.get(i));
    }
    return editor.commit();
}

And to read:

public void loadArray(Context context) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    _validContactsPhones.clear();
    int size = sharedPreferences.getInt("Status_size", 0);
    for (int i = 0; i < size; i++) {
        _validContactsPhones.add(sharedPreferences.getString("Status_" + i, null));
    }
}
Reaz Murshed
  • 22,528
  • 12
  • 75
  • 92
Faz
  • 272
  • 2
  • 10

2 Answers2

1

No, its not a good idea to store a huge list of String like contacts in SharedPreference.

There's no specific limit of size for the stored SharedPreference in your application as its stored in the /data/data/[package name]/shared_prefs/[app name].xml. Since SharedPreferences are stored in an XML file it lacks the strong transaction support of SQLite. Hence I would recommend to store this kind of data in a SQLite database.

Another thing which needs to keep in mind that, the lowest size limit that I am aware of will be your amount of free heap space, as SharedPreferences reads that entire XML file's contents into memory.

The answer is mostly copied from here.

Community
  • 1
  • 1
Reaz Murshed
  • 22,528
  • 12
  • 75
  • 92
0

You can save custom array list using Gson library.

1) First you need to create function to save array list to SharedPreferences.

public void saveArray(ArrayList<String> contacts) {

        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(_context);
        SharedPreferences.Editor editor = sp.edit();
        Gson gson = new Gson();
        String json = gson.toJson(contacts);
        editor.putString("Status_List", json);
        editor.apply(); 

    }

2) You need to create function to get array list from SharedPreferences.

public void loadArray(Context context)
{
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    _validContactsPhones.clear();
    Gson gson = new Gson();
    String json = prefs.getString("Status_List", "");
    Type type = new TypeToken<ArrayList<String>>() {}.getType();
    ArrayList<String> temp = gson.fromJson(json, type);
    _validContactsPhones.addAll(temp);
}
Jitesh Prajapati
  • 2,661
  • 4
  • 28
  • 47