gpt4 book ai didi

java - 空对象引用 Android 上的共享首选项

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:30:20 30 4
gpt4 key购买 nike

我是 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

最佳答案

这是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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com