I need to save some variables of my main Activity when the user jumping to another pages (activities) of my application. The official reference (http://developer.android.com/reference/android/app/Activity.html#SavingPersistentState) is provide to do saving persistent state by using the next code:
public class CalendarActivity extends Activity {
...
static final int DAY_VIEW_MODE = 0;
static final int WEEK_VIEW_MODE = 1;
private SharedPreferences mPrefs;
private int mCurViewMode;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences mPrefs = getSharedPreferences();
mCurViewMode = mPrefs.getInt("view_mode" DAY_VIEW_MODE);
}
protected void onPause() {
super.onPause();
SharedPreferences.Editor ed = mPrefs.edit();
ed.putInt("view_mode", mCurViewMode);
ed.commit();
}
}
When I implemented this part of code to my application (a little difference instead of ed.putInt I use ed.putBoolean) and run it, I got an error in LOGCat.
10-21 15:00:42.956: ERROR/AndroidRuntime(26590): FATAL EXCEPTION: main
10-21 15:00:42.956: ERROR/AndroidRuntime(26590):
java.lang.RuntimeException: Unable to pause activity
{com.example.android.Pitbul/com.example.android.Soft.Commander}:
java.lang.NullPointerException 10-21 15:00:42.956:
ERROR/AndroidRuntime(26590): at
android.app.ActivityThread.performPauseActivity(ActivityThread.java:2731)
10-21 15:00:42.956: ERROR/AndroidRuntime(26590): at
android.app.ActivityThread.performPauseActivity(ActivityThread.java:2678)
10-21 15:00:42.956: ERROR/AndroidRuntime(26590): at
android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3259)
10-21 15:00:42.956: ERROR/AndroidRuntime(26590): at
android.app.ActivityThread.access$1600(ActivityThread.java:132) 10-21
15:00:42.956: ERROR/AndroidRuntime(26590): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1042)
… 10-21 15:00:42.956: ERROR/AndroidRuntime(26590): Caused by:
java.lang.NullPointerException 10-21 15:00:42.956:
ERROR/AndroidRuntime(26590): at
com.example.android.Soft.Commander.onPause(Commander.java:355) 10-21
15:00:42.956: ERROR/AndroidRuntime(26590): at
android.app.Activity.performPause(Activity.java:4032) 10-21
15:00:42.956: ERROR/AndroidRuntime(26590): at
android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1337)
10-21 15:00:42.956: ERROR/AndroidRuntime(26590): at
android.app.ActivityThread.performPauseActivity(ActivityThread.java:2708)
10-21 15:00:42.956: ERROR/AndroidRuntime(26590): … 12 more
So, the error is happen on the
SharedPreferences.Editor ed = mPrefs.edit(); string.
Why this happened? What I need to fix this problem? I really need to save some variables and read them when user back on main activity screen.
do it like this way:
You are doing wrong in this line:
making it local variable in
onCreate(), so the global variable couldn’t be initialized which causeNullPointerExceptioninonPause()