gpt4 book ai didi

android - 如何从 SharedPreferences 计算具有整数值的键

转载 作者:行者123 更新时间:2023-11-29 19:23:12 25 4
gpt4 key购买 nike

我想使用 SharedPreferences 中的键计算 2 个值。这是我的代码

这是我的第一个 Activity

SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt(A1, option_scoreA1);
editor.commit();
Intent intent = new Intent(QuestionActivity.this, SecondActivity.class);
startActivity(intent);

这是我的第二个 Activity

   SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt(A2, option_scoreA4);
editor.commit();
Intent intent = new Intent(SecondActivity.this, TestFinalActivity.class);
startActivity(intent);

这是我的最后一个 Activity

protected QuestionActivity activity1;
protected SecondActivity activity2;

String c = activity1.A1;
String b = activity2.A2;

String A = c + b ;

@Bind(R.id.hasil)
TextView hasil;

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

public void total() {
hasil = (TextView) findViewById(R.id.hasil);
hasil.setText(A);
}

我想对键 A1 和 A2 的每个值求和。但是我得到的是 key ,而不是我对它们求和时的值。

谢谢

最佳答案

这是因为您将键添加或连接到变量 A 中。而且你要计算int所以你最好把总结果变成float或int数据类型,对吧?

做如下所示的事情

当您在 QuestionActivity 类中提交的实例时,非常重要的是制作两个键

public static final String KEY_A = "ka";
public static final String KEY_B = "kb";


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

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

int a = sharedPreferences.getInt(QuestionActivity.KEY_A, 0);
int b = sharedPreferences.getInt(QuestionActivity .KEY_B, 0);
A = a+b;

total();
}

因为它是整数,你需要将结果转换成字符串格式。

public void total() {
hasil = (TextView) findViewById(R.id.hasil);
hasil.setText(String.valueOf(A));
}

SharedPreference starting guide

关于android - 如何从 SharedPreferences 计算具有整数值的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41958879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com