我正在尝试学习 SharedPreferences,但出现错误。
我的布局有一个按钮可以对该方法做出反应doThis
这是我的java:
package com.example.sharedprefs;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
int i = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void doThis (View view){
i++;
SharedPreferences sharedPref = getSharedPreferences("FileName",MODE_PRIVATE);
SharedPreferences.Editor prefEditor = sharedPref.edit();
prefEditor.putInt("userChoice",i);
prefEditor.commit();
int number = sharedPref.getInt("userChoice", 0);
Toast.makeText(getApplicationContext(), number, Toast.LENGTH_LONG).show();
}
}
我唯一能在 logcat 中指出的是10-15 19:28:17.707: E/AndroidRuntime(16657): Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x1
你的吐司不正确。您将一个数字传递到 toast 中,希望它给出一个字符串,而不是认为它应该查找字符串资源值。尝试:
Toast.makeText(getContext(), number + "" , Toast.LENGTH_LONG).show();
编辑,除此之外,你的代码很好。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)