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;
}
}