以下代码出了什么问题?
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();
}
}
logcat
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)
答案 0 :(得分:2)
根据您发布的代码和您的logcat,您不会实例化您的SharedPreferences。
答案 1 :(得分:1)
你需要加载你的偏好,这样的事情应该这样做。把它放在onCreate上。
mPreferences = android.preference.PreferenceManager
.getDefaultSharedPreferences(this);