-2

I've been spending a lot of time trying to figure out the best method for saving a list of strings. My activity displays an edittext to input a string, a button to add it, and then the listview which displays the added string and all previously added strings. I think SQLite is overkill for this, but I can't figure out how to store a List in Shared Preferences. I've heard people mention JSON and GSON, though I have no experience with either and I'm not sure which option is best.

I'd really appreciate some advice as to which method would work best for this situation. Thanks in advance everyone.

domi91c
  • 1,962
  • 4
  • 23
  • 38

1 Answers1

1

You can use SharedPreference to save a list of strings. If you have more structured data, then using database might be better to manage else you can use Sharedreference to save and get the list as follows:

//Function to get the array in SharedPreference
Public String[] loadArray(String arrayName) {  
    SharedPreferences prefs = getSharedPreferences("preferencename", 0);  
    int size = prefs.getInt(arrayName + "_size", 0);  
    String array[] = new String[size];  
    for(int i=0;i<size;i++)  
        array[i] = prefs.getString(arrayName + "_" + i, null);  
    return array;  
}  

//Function to save the array in SharedPreference
public boolean saveArray(String[] array, String arrayName) {   
    SharedPreferences prefs = getSharedPreferences("preferencename", 0);  
    SharedPreferences.Editor editor = prefs.edit();  
    editor.putInt(arrayName +"_size", array.length);  
    for(int i=0;i<array.length;i++)  
        editor.putString(arrayName + "_" + i, array[i]);  
    return editor.commit();  
}

So for saving an array call:

String [] yourList; // Load the array with values
saveArray(yourList, "nameOfList");

To load the array from shared preferences

String [] arrName = loadArray("nameOfList");

See How to properly use load array and save array methods? and Save ArrayList to SharedPreferences for more.

Community
  • 1
  • 1
Shobhit Puri
  • 25,769
  • 11
  • 95
  • 124