Question

I am currently trying to implement SharedPreferences to save and load an ArrayList of objects. I have one button set to call saveFood() and another which calls loadFood().

public void saveFood(View view) {

    SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
    text = (TextView)(findViewById(R.id.feedback));

    editor.putInt("size", foodList.size());
    for (int y=0; y<foodList.size(); y++){
        editor.putInt(Integer.toString(y), foodList.get(y).getItemIdInt());
        editor.putString(Integer.toString(y)+"a", foodList.get(y).getItemName());
        editor.putInt(Integer.toString(y)+"b", foodList.get(y).getTime());
    }

    text.setText("saved");
}

public void loadFood(View view){

    int idNum = 0;
    int time = 0;
    int size = 0;
    String itemName;

    text = (TextView)(findViewById(R.id.feedback));

    SharedPreferences prefs = getPreferences(MODE_PRIVATE); 
    size = prefs.getInt("size", -1);

    if(size != -1){
        for (int x=0; x<size; x++){
            idNum = prefs.getInt(Integer.toString(x), -1);
            itemName = prefs.getString(Integer.toString(x)+"a", null);
            time = prefs.getInt(Integer.toString(x)+"a", -1);

            ObjectItem newFood = new ObjectItem(idNum, itemName, time);
            foodList.add(newFood);
        }

        text.setText("load successful");
    }
    else text.setText("error");


}

When the program is running and I click the save button, the saved message appears as expected. However, every time I click the load button I get the error feedback (getInt returned -1 for some reason).

Could anyone explain why this is happening?

Was it helpful?

Solution

You are never commiting your changes to the SharedPreferences. Try this:

SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
text = (TextView)(findViewById(R.id.feedback));

editor.putInt("size", foodList.size());
for (int y=0; y<foodList.size(); y++){
    editor.putInt(Integer.toString(y), foodList.get(y).getItemIdInt());
    editor.putString(Integer.toString(y)+"a", foodList.get(y).getItemName());
    editor.putInt(Integer.toString(y)+"b", foodList.get(y).getTime());
}

editor.commit(); // Save the changes
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top