我的适配器中的SharedPreferences

时间:2016-01-16 16:27:22

标签: java android sharedpreferences android-adapter

空指针异常错误..我尝试访问适配器中的sharedpreferences但不知道为什么它显示一些NullPointerException。这是日志和代码。

01-16 21:20:05.546  15405-15405/com.adequatsol.hdwallpaper E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.adequatsol.hdwallpaper, PID: 15405
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.adequatsol.hdwallpaper/com.adequatsol.hdwallpaper.FullImageActivity}: 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.app.ActivityThread.performLaunchActivity(ActivityThread.java:2546)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
        at android.app.ActivityThread.access$900(ActivityThread.java:177)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:145)
        at android.app.ActivityThread.main(ActivityThread.java:5942)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
 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:184)
        at com.adequatsol.hdwallpaper.ImageAdapter.<init>(ImageAdapter.java:47)
        at com.adequatsol.hdwallpaper.FullImageActivity.<init>(FullImageActivity.java:28)
        at java.lang.reflect.Constructor.newInstance(Native Method)
        at java.lang.Class.newInstance(Class.java:1650)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1079)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2536)

这是我的代码snipet

SharedPreferences sharedPreferences ;


public Integer [] selectedArray ;
public ImageAdapter(Context c){
    mContext = c;
    sharedPreferences = mContext.getSharedPreferences("MyPref", 0);
    int opt = sharedPreferences.getInt("option", 0);
    switch (opt)
    {
        case 1:
            selectedArray = mThumbIds ;
            break;
        case 2:
            selectedArray = landThumbIds ;
            break;
        case 3:
            selectedArray = carsThumbIds ;
            break;
    }

}

1 个答案:

答案 0 :(得分:0)

传递您的活动背景

gridView.setAdapter(new ImageAdapter(YourActivity.this));