How to save the state of Activity – Android

onSaveInstanceState, onRestoreInstanceState , save preferences

int mCurrentPhotoIndex = 0;
   @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt("photo_index", mCurrentPhotoIndex);
        super.onSaveInstanceState(outState);
    }
 
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        mCurrentPhotoIndex = savedInstanceState.getInt("photo_index");
        super.onRestoreInstanceState(savedInstanceState);
    }
 
// or save preferences for new start of Activity in onStop
//onCreate or onResume or onStart etc.
public void loadPreferences() {
		SharedPreferences settings = getSharedPreferences(F.PREFERENCES_NAME, 0);
		mCurrentPhotoIndex = settings.getInt("mCurrentPhotoIndex",mCurrentPhotoIndex);
	// String_sOtazka = settings.getString("_sOtazka", _sOtazka);
 
 
}
// onStop
public void savePreferences() {
		SharedPreferences settings = getSharedPreferences(PREFERENCES_NAME, 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putInt("mCurrentPhotoIndex", mCurrentPhotoIndex);
                // String, boolean, float ...
		// editor.putString("mButton1", mButton1.getText().toString());
 
		editor.commit();
 
}
This entry was posted in Android Examples Code and tagged , . Bookmark the permalink.


Comments are closed.



3,240 views