记住共享首选项中的上一个数组

时间:2017-12-14 12:48:10

标签: java android arrays sharedpreferences

关于sharedPreferences和int数组的快速问题。这是我的一些代码(相关位)。而我想要发生的是,如果用户做某事(保持模糊,因为它不相关),那么数组保持2在该位置。相反,如果每次我关闭应用程序或更改活动,那么阵列将重新成为没有两个人的所有人。这可能是一个微不足道的问题,对不起,如果是。

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

}

2 个答案:

答案 0 :(得分:1)

每次打开应用时,list变量都会初始化为所有变量。您需要将共享首选项中的列表加载到list变量中,而不是加载到isCorrect数组中,因为这是您在更新共享首选项中存储的列表时从中获取值的位置按钮。

或者在onCreate do:

list = isCorrect;

我认为它应该有用。

答案 1 :(得分:0)

您可以尝试两种解决方案。

解决方案1 ​​

使你的int数组静态,并参考Activity

public class SecondActivity extends AppCompatActivity {

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

public void startAQuestion(View view){ 
.
.

如何使用

SecondActivity.list[tappedQuestionmark]=2; 

解决方案2 使用savedInstance传递数组

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 
     }

}

我希望它会对你有所帮助!