1

Just a quick question regarding sharedPreferences and int arrays. This is some of my code (the relevant bits). And what I want to happen is if the user does something (keeping it vague because it is not relevant), then the array keeps a 2 in that position. Instead what happens is if everytime I close the app or change the activity, the array goes back to being all ones with no twos. This might be a trivial problem, sorry if it is.

public class SecondActivity extends AppCompatActivity {

    int[] list = { 1, 1, 1, 1, 1, 1 };

public void startAQuestion(View view){ 

    checkAnswerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) { 

                if(editText2.getText().toString().equals(mAnswer)) {

                    list[tappedQuestionmark]=2; 

                    storeIntArray("updateList", list);

                    Log.i("The array is ", Arrays.toString(list));
                }    
            }
            });
        }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        int[] isCorrect = getFromPrefs("updateList");

        Log.i("is Correct is ", Arrays.toString(isCorrect));

    }

    public void storeIntArray(String name, int[] array) {
        SharedPreferences.Editor edit = this
                .getSharedPreferences("com.example.sid.sharedpreferencedemo", Context.MODE_PRIVATE).edit();
        edit.putInt("Count_" + name, array.length).commit();
        int count = 0;
        for (int i : array) {
            edit.putInt("IntValue_" + name + count++, i).commit();
        }
        edit.commit();
    }

    public int[] getFromPrefs(String name) {
        int[] ret;
        SharedPreferences prefs = this.getSharedPreferences("com.example.sid.sharedpreferencedemo",
                Context.MODE_PRIVATE);
        int count = prefs.getInt("Count_" + name, 0);
        ret = new int[count];
        for (int i = 0; i < count; i++) {
            ret[i] = prefs.getInt("IntValue_" + name + i, i);
        }
        return ret;
    }

}
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
mathsislife
  • 57
  • 1
  • 9

2 Answers2

1

Every time you open the app your list variable gets initialized to all ones. You need to load the list from shared preferences into your list variable not into the isCorrect array, because that is where you take the values from when you update the list stored in shared preferences on the click of a button.

Or in onCreate do:

list = isCorrect;

and I think it should work.

gabrielkerekes
  • 468
  • 4
  • 10
  • One last problem that I can't work out. When starting from the beginning, the variable isCorrect equals []. So it crashes because there's nothing in there. How would I initialise this without ruining the rest of the code? Thanks! – mathsislife Dec 14 '17 at 14:37
  • I should also say this happens when I also did your first suggestion. I also tried to make list static and it still didn't work. Any help much appreciated. – mathsislife Dec 14 '17 at 15:02
0

There are 2 solutions you can try.

Solution 1

make your int array static, and refer to the Activity

public class SecondActivity extends AppCompatActivity {

   public static int[] list = { 1, 1, 1, 1, 1, 1 };

public void startAQuestion(View view){ 
.
.

How to use

SecondActivity.list[tappedQuestionmark]=2; 

Solution 2 use the savedInstance to pass your array

public void onSaveInstanceState(Bundle outState){
    outState.putSerializable("list ", list);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
     list = savedInstanceState.getSerializable("list ");

     if(list  != null)
     {
          //Do something with list 
     }

}

I hope it will help you!

  • Hi many thanks for your reply! The first solution almost worked but still got overwritten when I closed the app and picked another box. What I mean is when I started the app the array was {1,1,1,1,1,1} I make 1 and 3 go to 2 as follows {1,2,1,2,1,1} then I would close the app and open again and make 0 go to 2 then it would show {2,1,1,1,1,1}. The second solution, android studio says they are incompatible types? I would be very grateful if you have any hints for either of them. Thanks – mathsislife Dec 14 '17 at 13:43
  • Sorry, I had no undestood. So take a look at this post https://stackoverflow.com/questions/7175880/how-can-i-store-an-integer-array-in-sharedpreferences – Guilherme Montanher Dec 14 '17 at 13:46