I have found a great tutorial about storing arrays in SharedPreferences. Every time I add one item to an array, I store it in SharedPreferences, but when loading the array I get null for all values. Size of the array is increased by 1 every time, but the elements are stored as null. Why?
String tname[] = new String[loadArray(t_name, this).length + 1];
for (int i=0; i<tname.length; i++)
{
Log.i("tname[" + i + "]", tname[i] + ""); //null
}
tname[tname.length-1] = et_name; //this is a string which is not null
saveArray(tname, t_name, NewSchedule.this);
public boolean saveArray(String[] array, String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("sp_name", 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();
}
public String[] loadArray(String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("sp_name", 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;
}
Am I using the found code the right way?
**SOLUTION based ony 10s’ answer:
String tname[] = new String[loadArray(t_name, this).length + 1];
String[] prevPrefs = loadArray(t_name, this);
for(int i=0; i<prevPrefs.length; i++) {
tname[i] = prevPrefs[i]; //0th element will be null, as well as e.g. the 4th when there are 3 elements
}
for (int i=0; i<tname.length; i++)
{
if (tname[i] == null) { //so we put the new value in place of the null
tname[i] = et_name;
}
}
//Arraylists are much handier than arrays
if (arr_names.size() > 0) arr_names.clear(); //first clear all elements
for (int i=0; i<tname.length; i++) {
if (tname[i] != null) arr_names.add(tname[i]);
}
for (int i=0; i<arr_names.size(); i++) {
if (arr_names.get(i) == null) {
arr_names.remove(i);
}
}
String[] tname2 = new String[arr_names.size()]; //create new array
for (int i=0; i<tname2.length; i++) //popluate new array
{
tname2[i] = arr_names.get(i);
}
saveArray(tname2, t_name, NewSchedule.this);
The problem is here:
This line does not create an array that is filled up with values: the
loadArray(t_name, this).length + 1actually returns a number. All this is actually translated as:which actually creates a new array of Strings that has null values.
Solution: you should then iterate among the items of a temporary
prevPrefs[]that is loaded from theloadArray()method of yours and add them in thetname[]like this:then you would have the array filled up with the values of the previous one and you can add to the last empty spot the new value as you already did.