我是 android 开发的新手,也许这是一个愚蠢的问题,但请帮助我。我在尝试保存 int 值时遇到此错误。
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
这是我的代码
SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
String value = "com.example.app.value";
int i = prefs.getInt(value, 0);
对于写
prefs.edit().putInt(number, i).apply();
我只想设置一个 SharedPreferences 并希望首先阅读它并将其写入 Activity 中。我该如何解决?
编辑
public class MainActivity extends Activity {
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "myprefs";
public static final String value = "key";
int i = sharedpreferences.getInt(value, 0);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
}
public void sendMessage(View view) {
i += 1;
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt(value, i);
editor.apply();
}
我设法用不同的方式保存了首选项,但我无法在 MainActivity extends Activity 类中读取它。
日志:
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int android.content.SharedPreferences.getInt(java.lang.String, int)' on a null object reference
Best Answer-推荐答案
这是 SharedPreferences 的示例
在 SharedPreferences 中保存 name :
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putString(key, name);
editor.apply();
从 SharedPreferences 中获取 name :
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
String name = sharedPreferences.getString(key, "default value");
更多详情请访问:http://developer.android.com/training/basics/data-storage/shared-preferences.html
更新代码:
public class MainActivity extends Activity {
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "myprefs";
public static final String value = "key";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
int i = sharedpreferences.getInt(value, 0);
//use the value of i where needed.
}
public void saveMessage(View view) {
i += 1;
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt(value, i);
editor.apply();
}
关于java - 空对象引用 Android 上的共享首选项,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/31142325/
|