使用SharedPreferences

时间:2017-05-25 04:24:29

标签: java android nullpointerexception sharedpreferences

我一直在键盘上敲打几个小时。我想在我的应用程序中为单独的统计信息活动存储递增的整数。我正在尝试使用共享首选项来实现此目的。然而,在我最近的尝试中,这是我得到的最远的,该程序抛出异常。

我的代码:

public class LootChest extends AppCompatActivity {
    public static final String prefName = "prefsFile";
    SharedPreferences settings = getApplicationContext().getSharedPreferences(prefName, 0); //line 25
    int rollCountS = settings.getInt("Roll Count", 0);
    int rollCount = 0; //to be incremented

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loot_chest);
    }

    public void openChest(View v) {
        SharedPreferences.Editor editor = settings.edit();
        editor.putInt("Roll Count", rollCount);
        rollCount = rollCountS + 1;

例外:

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 at android.content.ContextWrapper
.getSharedPreferences(ContextWrapper.java:171)
at net.zingrook.mobiloot.LootChest.<init>(LootChest.java:25)

我已经阅读了很多关于实现这一点的线程,并查看了Android文档并且我没有想法。谢谢你的帮助。

3 个答案:

答案 0 :(得分:4)

您正在开始活动生命周期之前初始化sharedPreference对象。

将初始化移至onCreate

public static final String prefName = "prefsFile";
    SharedPreferences settings;  //line 25
    int rollCountS;
    int rollCount = 0;
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loot_chest);
        settings = getApplicationContext().getSharedPreferences(prefName, 0); 
    }

答案 1 :(得分:1)

只需以这种方式更改您的代码即可。

public class LootChest extends AppCompatActivity {
    public static final String prefName = "prefsFile";
    SharedPreferences settings;  //line 25
    int rollCountS;
    int rollCount = 0; //to be incremented

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loot_chest);
        settings = getApplicationContext().getSharedPreferences(prefName, 0);
        rollCountS = settings.getInt("Roll Count", 0);
    }

答案 2 :(得分:0)

我的观点

public class LootChest extends AppCompatActivity {
public static final String prefName = "prefsFile";
SharedPreferences settings;
SharedPreferences.Editor editor;
int rollCountS;
int rollCount = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_loot_chest);
    settings=getApplicationContext().getSharedPreferences(prefName, 0);
    editor = settings.edit();
    rollCountS= settings.getInt("Roll Count", 0);
}

public void openChest(View v) {
    editor.putInt("Roll Count", rollCount);
    rollCount = rollCountS + 1;