0

I have an array of string, size 100. I have entered data in this string array. Now, I want to store this array of string using SharedPreferences.

So my question is that, is it possible to store the entire array of string instead of storing each string individually using SharedPreferences. If so, how that can be done.

The code I have written is used to store data individually using the loop. But I want to store the entire string array without using the loop.

Code I have written for storing individually is

SharedPreferences preferencesWrite  = c.getSharedPreferences("myPreferences", 0);
SharedPreferences.Editor editor  = preferencesWrite.edit();

for(int i=0; i< 100; i++)
{
    editor.putString("dtHistory" + Integer.toString(i), m_dtHistory[i];

}
editor.commit();
iknow
  • 8,358
  • 12
  • 41
  • 68
AndroidDev
  • 4,521
  • 24
  • 78
  • 126
  • You can try this: https://stackoverflow.com/questions/14981233/android-arraylist-of-custom-objects-save-to-sharedpreferences-serializable/34763035#34763035 – Mete Oct 26 '18 at 12:48

2 Answers2

0

Yes it,s Possible to Store array in form of String

you should do something like this :

    SharedPreferences preferencesWrite  = c.getSharedPreferences("myPreferences", 0);
    SharedPreferences.Editor editor  = preferencesWrite.edit();

     Gson gson = new Gson();
     ArrayList<ModelClass>favorites = new ArrayList<>();

     String jsonFavorites = gson.toJson(favorites);
     editor.putString("your sharedPref NTT", jsonFavorites);
     editor.apply();
Rocky
  • 457
  • 4
  • 11
0

SharedPreferences only allow saving single items per entry - this limitation is enforced so that users can only store, as the name suggests, "preferences" - a flag, a string, a number, and so on. This is to eliminate the unnecessary use of an sqlite database for trivial items.

There is, however, a new method for sharedPreferences (API 11) that allows you to store a set of strings. It's called putStringSet and you can check it out here.

josephus
  • 8,284
  • 1
  • 37
  • 57
  • Using shared preferences i am storing only single item only that is note count and it is number. The string i have stored using file – AndroidDev Feb 29 '12 at 06:10