来自PreferenceManager.getDefaultSharedPreferences的空指针异常

时间:2016-07-05 15:03:16

标签: java android nullpointerexception sharedpreferences

这是我所创建的应用程序类的代码,我使用它来保存领域数据库的默认配置,并保留2个静态方法来处理SharedPreferences其中一个我获得NullPointerException }

public class BucketDropsApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        RealmConfiguration config=new RealmConfiguration.Builder(this).build();
        Realm.setDefaultConfiguration(config);
    }

    public static void save(Context context,int state){
        SharedPreferences mPrefs= PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor mEditor=mPrefs.edit();
        mEditor.putInt("State",state);
        mEditor.apply();
    }

    public static int load(Context context){
        SharedPreferences mPrefs= PreferenceManager.getDefaultSharedPreferences(context);
        int stateType=mPrefs.getInt("State", StateType.NONE);
        return stateType;
    }

}

这是MainActivity的类:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mToolbar = (Toolbar) findViewById(R.id.main_toolBar);
    setSupportActionBar(mToolbar);
    mBtnAdd = (Button) findViewById(R.id.btn_trigger_dialog);
    mBtnAdd.setOnClickListener(mBtnAddListener);
    mRealm = Realm.getDefaultInstance();
    int filterOption = BucketDropsApp.load(this);
    loadResults(filterOption);
    mEmptyView = findViewById(R.id.emptyScreen);
    mRecycler = (BucketDropRecycler) findViewById(R.id.rv_drops);
    mRecycler.addItemDecoration(new Divider(this, LinearLayoutManager.VERTICAL));
    mRecycler.hideIfEmpty(mToolbar);
    mRecycler.showIfEmpty(mEmptyView);
    mAdapter = new DropsAdapter(this, mResults,  mAddListener, mMarkListener,mRealm);
    mRecycler.setAdapter(mAdapter);
    CustomCallback callback = new CustomCallback(mAdapter);
    ItemTouchHelper helper = new ItemTouchHelper(callback);
    helper.attachToRecyclerView(mRecycler);
    initBackgroundImage();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    boolean handled = true;
    int filterOption = StateType.NONE;
    switch (id) {
        case R.id.menu_add:
            showDialogAdd();
            break;
        case R.id.menu_least:
            filterOption = StateType.LEAST_TIME_LEFT;
            break;
        case R.id.menu_most:
            filterOption = StateType.MOST_TIME_LEFT;
            break;
        case R.id.menu_complete:
            filterOption = StateType.COMPLETE;
            break;
        case R.id.menu_incomplete:
            filterOption = StateType.INCOMPLETE;
            break;
        default:
            handled = false;
            break;
    }
    loadResults(filterOption);
    BucketDropsApp.save(this, filterOption);
    return handled;
}

private void loadResults(int filterOption) {
    switch (filterOption) {
        case StateType.NONE:
            mResults = mRealm.where(Drop.class).findAllAsync();
            break;
        case StateType.LEAST_TIME_LEFT:
            mResults = mRealm.where(Drop.class).findAllSortedAsync("when");
            break;
        case StateType.MOST_TIME_LEFT:
            mResults = mRealm.where(Drop.class).findAllSortedAsync("when", Sort.DESCENDING);
            break;
        case StateType.COMPLETE:
            mResults = mRealm.where(Drop.class).equalTo("completed", true).findAllAsync();
            break;
        case StateType.INCOMPLETE:
            mResults = mRealm.where(Drop.class).equalTo("completed", false).findAllAsync();
            break;
    }
    mResults.addChangeListener(mChangeListener);
}

当我尝试运行应用程序时,这就是logcat中弹出的内容

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.compassasu.bucketdrops/com.compassasu.bucketdrops.ActivityMain}: java.lang.NullPointerException
                                                                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
                                                                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
                                                                          at android.app.ActivityThread.access$800(ActivityThread.java:135)
                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                          at android.os.Looper.loop(Looper.java:136)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:5001)
                                                                          at java.lang.reflect.Method.invokeNative(Native Method)
                                                                          at java.lang.reflect.Method.invoke(Method.java:515)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
                                                                          at dalvik.system.NativeStart.main(Native Method)
                                                                       Caused by: java.lang.NullPointerException
                                                                          at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:374)
                                                                          at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:369)
                                                                          at com.compassasu.bucketdrops.BucketDropsApp.load(BucketDropsApp.java:33)
                                                                          at com.compassasu.bucketdrops.Recycler.DropsAdapter.update(DropsAdapter.java:64)
                                                                          at com.compassasu.bucketdrops.Recycler.DropsAdapter.<init>(DropsAdapter.java:51)
                                                                          at com.compassasu.bucketdrops.ActivityMain.onCreate(ActivityMain.java:105)
                                                                          at android.app.Activity.performCreate(Activity.java:5231)
                                                                          at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
                                                                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
                                                                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233) 
                                                                          at android.app.ActivityThread.access$800(ActivityThread.java:135) 
                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
                                                                          at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                          at android.os.Looper.loop(Looper.java:136) 
                                                                          at android.app.ActivityThread.main(ActivityThread.java:5001) 
                                                                          at java.lang.reflect.Method.invokeNative(Native Method) 
                                                                          at java.lang.reflect.Method.invoke(Method.java:515) 
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) 
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) 
                                                                          at dalvik.system.NativeStart.main(Native Method) 

1 个答案:

答案 0 :(得分:0)

您的活动是否扩展了android.app.Application?。 如果是,那么你可以尝试按如下方式传递上下文,即代替此,传递getApplicationContext()

mAdapter = new DropsAdapter(getApplicationContext(), mResults,  mAddListener, mMarkListener,mRealm);

可能想参考以下链接:

Should I use getApplicationContext or Activity.this in a long running AsyncTask

Some notes about Android Context