-3

下面的代码做错了什么?

SharedPreferences mPreferences;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    setContentView(R.layout.splash);
        new Handler().postDelayed(new Runnable() {

            public void run() {
                init();
                callFunc();
            }

        }, SPLASH_DISPLAY_LENGHT);
        // }
    }

    boolean firstTime() {
        boolean firstTime = mPreferences.getBoolean("firstTime", true);
        if (firstTime) {
            SharedPreferences.Editor editor = mPreferences.edit();
            editor.putBoolean("firstTime", false);
            editor.commit();
            return true;
        } else {
            return false;
        }
    }

    void callFunc(){
        if(firstTime()){
            callDetailedScreen();           
        }
        else{
            CallMainScreen();   
        }
    }

日志猫

09-21 03:28:58.948: E/AndroidRuntime(314): FATAL EXCEPTION: main
09-21 03:28:58.948: E/AndroidRuntime(314): java.lang.NullPointerException
09-21 03:28:58.948: E/AndroidRuntime(314):  at com.x.y.Main.firstTime(Main.java:38)
09-21 03:28:58.948: E/AndroidRuntime(314):  at com.x.y.callFunc(Main.java:50)
09-21 03:28:58.948: E/AndroidRuntime(314):  at com.x.y.Main$2.run(Main.java:30)
09-21 03:28:58.948: E/AndroidRuntime(314):  at android.os.Handler.handleCallback(Handler.java:587)
09-21 03:28:58.948: E/AndroidRuntime(314):  at android.os.Handler.dispatchMessage(Handler.java:92)
09-21 03:28:58.948: E/AndroidRuntime(314):  at android.os.Looper.loop(Looper.java:123)
09-21 03:28:58.948: E/AndroidRuntime(314):  at android.app.ActivityThread.main(ActivityThread.java:4627)
09-21 03:28:58.948: E/AndroidRuntime(314):  at java.lang.reflect.Method.invokeNative(Native Method)
09-21 03:28:58.948: E/AndroidRuntime(314):  at java.lang.reflect.Method.invoke(Method.java:521)
09-21 03:28:58.948: E/AndroidRuntime(314):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-21 03:28:58.948: E/AndroidRuntime(314):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-21 03:28:58.948: E/AndroidRuntime(314):  at dalvik.system.NativeStart.main(Native Method)
4

2 回答 2

2

根据您发布的代码和您的 logcat,您没有实例化您的 SharedPreferences。

于 2012-09-20T22:08:49.507 回答
1

您需要加载您的首选项,应该这样做。把它放在 onCreate 中。

mPreferences = android.preference.PreferenceManager
            .getDefaultSharedPreferences(this);
于 2014-02-23T11:35:32.520 回答