循环得分并保存在数据库中

时间:2014-12-02 12:03:48

标签: android database

我在循环/添加分数时遇到问题。我在这里只是添加分数的方法/等式。任何人都可以帮助我循环吗?我的意思是,当单击一个按钮时,应该添加数据库中的相应分数。例如,我有一个相当于1的苹果和相当于5的浓缩牛奶,这应该自动总计为6(与我添加更多水果相同的过程)。所以这就是我在得分循环中的意思。

我也有一个计时器,我想要的是,当时间结束时,总和或总数也应该自动保存到数据库中。

任何人都可以帮我解决这个问题吗?

我用于添加的公式

private void calculate(){
    x = Integer.parseInt(tv3.getText().toString().replaceAll("\\s",""));
    y = Integer.parseInt(tv2.getText().toString().replaceAll("\\s",""));
    z = x + y;
    score.setText(Integer.toString(z));
}

1 个答案:

答案 0 :(得分:0)

首先将分数存储在全局int z

private int z = 0;
private void calculate(){
    x = Integer.parseInt(tv3.getText().toString().replaceAll("\\s",""));
    y = Integer.parseInt(tv2.getText().toString().replaceAll("\\s",""));
    z += (x + y);
    score.setText(Integer.toString(z));
}

然后,当您的计时器用完后,将此z存储到共享首选项中,如此

        final SharedPreferences.Editor editor = getSharedPreferences("Some Name",
Context.MODE_PRIVATE).edit(); (assuming you are in the activity)
        editor.putInt("totalScore", z);
        editor.apply();

您可以通过以下方式检索此值:

int z = getSharedPreferences("Some Name",
    Context.MODE_PRIVATE).getInt("totalScore", 0); //again, assuming you are in the MainActivity

如果您不在活动中,请使用

context.getSharedPreferences("Some Name", Context.MODE_PRIVATE)