我有兩個活動(MainActivity和Player)。在MainActivity中,我創建了兩種方法:如何在android中獲取getSharedPreferences?
private final long DEFAULTLONG = 0;
public long getTotalPlayTime(){
SharedPreferences sp = getApplicationContext().getSharedPreferences("TotalPlaybackTime", MODE_PRIVATE);
long tempTotalTime = sp.getLong("totalPlayTime", DEFAULTLONG);
return tempTotalTime;
}
public void updateTotalPlayTime(){
SharedPreferences sp = getSharedPreferences("TotalPlaybackTime", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putLong("totalPlayTime", totalPlayTime);
editor.commit();
}
當我從Player活動調用這兩種方法時,我的應用程序崩潰。 我已經實例化球員在MainActivity並呼籲通過這條線的方法:
if (preferenceScheduler++ == 10) {
f.updateTotalPlayTime();
seconds2 = (f.getTotalPlayTime()) % 60;
minutes2 = ((f.getTotalPlayTime() - seconds2))/60;
}
我不知道爲什麼,它給我的NullPointerException。
以下是完整的錯誤日誌:
java.lang.NullPointerException
at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:161)
at tushar.prime.primeplayer.MainActivity.updateTotalPlayTime(MainActivity.java:329)
at tushar.prime.primeplayer.player.update(player.java:506)
at tushar.prime.primeplayer.player.access$000(player.java:40)
at tushar.prime.primeplayer.player$1.run(player.java:133)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5297)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
發佈調用'updateTotalPlayTime()'的代碼 - 你可能在那裏實例化了一個有'new'的活動(你不應該)。 – laalto 2015-02-09 12:39:36
是的你是對的。我已經在Player中實例化了MainActivity:'private static MainActivity f = new MainActivity();' – Tushar 2015-02-09 12:43:49
也許你在super.onCreate()方法之前調用updateTotalPlayTime,在super.onCreate()之後調用,否則你可以使用application context.getSharedPreferences () – 2015-02-09 12:50:10