I came across to the many questions asking about to store some kind data in Shared-preferences such as String[] array. Many of these questions are answered with "Use a database".
But here i will show you a perfect piece of code by which you can store and retrieve an String[] array in Shared-preferences.
You can put these two methods in your utility class and call than from the class where you want to store and retrieve data.
This is the method to save your String[] array in Shared-preferences.
public boolean saveArrayData(String[] array, String arrayName, Context mContext) {
SharedPreferences prefs = mContext.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();
}
Now to get the array back, you just have to call the getArrayData.
public String[] getArrayData(String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
int size = prefs.getInt(arrayName + "_ ", 0);
for(int i=0 ; i<array.length ; i++){
editor.getString(arrayName + "_ " + i, array[i]);
}
return editor.commit();
}
This is the whole process of storing and retrieving String[] array by using Shared-preferences.
Hope you like it...
0 Comment(s)