我正在尝试创建一个计算时间的应用程序。
我的情况:
我有一个包含很多元素的 RecyclerView,每个元素都有不同的 time
属性。
现在,当单击一个元素时,然后单击另一个元素,我希望对所有这些属性求和并将最终结果显示在另一个 Activity 中。 所以我想做的是使用 SharedPrefernces 来实现这一点:
private void getTime(int time) {
SharedPreferences sharedPreferences = mContext.getSharedPreferences("sharedPrefs", MODE_PRIVATE);
int time0 = sharedPreferences.getInt("TimeRetrieve", 0);
int sum = time0 + time;
SharedPreferences sharedPreferences2 = mContext.getSharedPreferences("sharedPrefs", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences2.edit();
editor.putInt("Time", sum);
editor.apply();
TimeRetrieve
获取在 TextView 上显示的总时间,因此如果是第一次,它当然默认为 0。
之后,它应该将检索到的 int 与刚刚被单击然后保存在另一个 SharedPref 中的 Item 的 int 相加:Time
。
Time
被发送到 TextView,在那里它被 TimeRetrieve
但是他的不起作用..
最佳答案
首先,您使用了 2 个不同的键:TimeRetrieve
和 Time
。所以,你不能计算总和。
其次,为什么要使用 2 个 SharedPreferences
对象?只需要一个。
第三,您不需要在这里使用 SharedPreferences
。您只需在一个变量中求和您想要的内容,然后将其传递给带有额外 bundle 的其他 Activity。
关于java - 使用 SharedPrefernces 对来自 RecyclerView 的整数求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56874122/