简体   繁体   中英

How to save an activity state if I press back button?

I have 2 activities: In the first activity the user sets his name, and then he clicks next to open the second activity, to update his profile picture. I want that, if he decides to go back to edit his name, and if he already chose a picture, save the state where the image view is loaded with the picture he chose. Currently what's happening is that if I click back, and the next again, the image view sets back to the default profile picture icon.

I tried using SharedPreferences, but I must be doing something wrong:

 ..........

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_picture);
        LoadPreferences();
    }

    @Override
    public void onBackPressed() {

    SavePreferences();
    super.onBackPressed();
    }

    private void SavePreferences(){
        SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean("state", backButton.isEnabled());
        editor.commit(); 
    }

    private void LoadPreferences(){
        SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
        Boolean  state = sharedPreferences.getBoolean("state", true);
        backButton.setEnabled(state);
    }
}

I'm a beginner, but I feel that there is fundamentaly wrong code here, but I can't find it.

You're using the shared preferences thinking it will save the state of your activity, but all your code does is saving the state of the back button and whether it's enabled or not. Try saving the details you want to keep instead, such as name and a reference to the photo from where you're saving it.

If for example you have an EditText where the user type in their name try the following:

String name = yourEditText.getText().toString();

SharedPreferences preferences =PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name", name);
editor.apply();

then in your activity's onResume fetch the values and populate your views again:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name", null);
yourEditText.setText(name);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM