空对象上的共享首选项引用 Android
我是机器人开发的新手,也许这是一个愚蠢的问题,但请帮助我。我在尝试保存int值时收到此错误。
Caused by: java.lang.NullPointerException: 尝试在 null 对象引用上调用虚拟方法 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)'
这是我的代码
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();
我只想设置一个共享首选项,并希望首先阅读它并将其写入活动。我该如何解决?
编辑
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扩展活动类中阅读它。
日志:
Caused by: java.lang.NullPointerException: 尝试在空对象引用上调用接口方法 'int android.content.SharedPreferences.getInt(java.lang.String, int)'