Error : Attempt to invoke interface method 'java.util.Map android.content.SharedPreferences.getAll()' on a null object reference
Error : Attempt to invoke interface method 'java.util.Map android.content.SharedPreferences.getAll()' on a null object reference
多年来一直坚持这个问题,并尝试了多种我认为可以解决的问题,但我对 Java 很陌生,无法弄清楚。
所以我宣布这个东西:
public SharedPreferences prefs;
public SharedPreferences.Editor editor;
然后在后面的方法中:
public void SaveInsult(View view) {
String saved = insult.getText().toString();
int number = prefs.getAll().size();
int newKey = number + 1;
String newKeyString = "" + newKey;
editor.putString(newKeyString, saved);
editor.commit();
Toast.makeText(getApplicationContext(), R.string.addedFavs, Toast.LENGTH_SHORT).show();
}
我的应用程序将正常启动,但是当我 运行 按钮上的这段代码单击按钮时,我收到错误消息:
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Map android.content.SharedPreferences.getAll()' on a null object reference
我知道我遗漏了一些我不知道在哪里的东西。
您没有初始化首选项:
SharedPreferences prefs = context.getSharedPreferences("Your_Key", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
确保在 editor.putString(newKeyString, saved);
之前调用它
多年来一直坚持这个问题,并尝试了多种我认为可以解决的问题,但我对 Java 很陌生,无法弄清楚。
所以我宣布这个东西:
public SharedPreferences prefs;
public SharedPreferences.Editor editor;
然后在后面的方法中:
public void SaveInsult(View view) {
String saved = insult.getText().toString();
int number = prefs.getAll().size();
int newKey = number + 1;
String newKeyString = "" + newKey;
editor.putString(newKeyString, saved);
editor.commit();
Toast.makeText(getApplicationContext(), R.string.addedFavs, Toast.LENGTH_SHORT).show();
}
我的应用程序将正常启动,但是当我 运行 按钮上的这段代码单击按钮时,我收到错误消息:
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Map android.content.SharedPreferences.getAll()' on a null object reference
我知道我遗漏了一些我不知道在哪里的东西。
您没有初始化首选项:
SharedPreferences prefs = context.getSharedPreferences("Your_Key", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
确保在 editor.putString(newKeyString, saved);