【发布时间】:2015-10-17 07:57:06
【问题描述】:
我有一个包含两个显示 int 值的 TextView 的活动。当用户单击按钮时,这些值会逐渐变化(1、2、3 等等...)。我使用SharedPreferences 通过按钮单击来存储该值。当我关闭应用程序并再次打开它时,这些值会正确显示在 TextViews 中,但如果它们发生变化,则应该从之前存储的值中添加它们。问题是它们从零开始计数。
这是我的代码:
public class Roulette1 extends ActionBarActivity {
Button button0, button1;
int click_button0, click_button1;
public static final String button0Str = "button0Key";
public static final String button1Str = "button1Key";
public static final String MyPREFERENCES = "MyPrefsRoulette1";
SharedPreferences sharedpreferences;
TextView times_0_tv;
TextView times_1_tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout1);
times_0_tv = (TextView) findViewById(R.id.times_0);
times_1_tv = (TextView) findViewById(R.id.times_1);
button0 = (Button) findViewById(R.id.button0);
button1 = (Button) findViewById(R.id.button1);
final TextView total_clicks_tv = (TextView) findViewById(R.id.total_clicks);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
click_button1 = click_button1 + 1;
int total_clicks = click_button0 + click_button1;
total_clicks_tv.setText(String.valueOf(total_clicks));
times_0_tv.setText(click_button0);
times_1_tv.setText(click_button1);
button0.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
click_button0 = click_button0 + 1;
int total_clicks = click_button0 + click_button1;
total_clicks_tv.setText(String.valueOf(total_clicks));
times_0_tv.setText(click_button0);
times_1_tv.setText(click_button1);
}
});
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (sharedpreferences.contains(button0Str))
{
times_0_tv.setText(sharedpreferences.getString(button0Str, ""));
}
if (sharedpreferences.contains(button1Str))
{
times_1_tv.setText(sharedpreferences.getString(button1Str, ""));
}
}
public void run1(View view) {
SharedPreferences.Editor editor = sharedpreferences.edit();
String times0string = times_0_tv.getText().toString();
String times1string = times_1_tv.getText().toString();
editor.putString(button0Str, times0string);
editor.putString(button1Str, times1string);
editor.commit();
}
希望你有任何想法。谢谢!
【问题讨论】:
-
Problem is that they start to count from zero.。幸运的人。您甚至没有将它们初始化为零。或者另一个值。你应该得到一个编译时警告。 -
Shared preferences doesn't store int data。错误的。您正在尝试存储字符串。不是整数。
标签: android integer sharedpreferences textview android-button