Null对象参考Android上的共享首选项

Simbilli开发:

我是android开发的新手,也许这是一个愚蠢的问题,但请帮助我。尝试保存int值时出现此错误。

原因:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'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();

我只想设置一个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扩展Activity类中读取它。

日志:

原因:java.lang.NullPointerException:尝试在空对象引用上调用接口方法'int android.content.SharedPreferences.getInt(java.lang.String,int)'

阿南德·辛格(Anand Singh):

这是一个例子 SharedPreferences

要保存name在SharedPreferences中:

SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        Editor editor = sharedPreferences.edit();
        editor.putString(key, name);
        editor.apply();

要从nameSharedPreferences 获取

 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();
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章