Search code examples
javaandroidandroid-intentandroid-activitystartactivityforresult

How to retain value in second activity after re-clicking the button from MainActivity to launch the second activity?


I have 2 activities. First is MainActivity and second is SecondActivity.

MainActivity has a textView and buttoncalled "Launch". Using intent and startActivityForResult I am passing a list to SecondActivity.

SecondActivity has a spinner and 2 buttons;a select button and a cancel button.

On selection of an item from the spinner, when user clicks on Select button, the option chosen in the spinner is populated in the textView of MainActivity.

Now when the user again clicks on "Launch", SecondActivity launches however, the spinner doesn't hold the value the user had chosen last time, instead it shows the first value of the spinner.

Is their anyway, how I can retain the value selected in the SecondActivity chosen by the user in it's previous use.


Solution

  • When you close the SecondActivity, you should return the select item of spinner to MainActivity. If it is MainActiviy can get that value in this function :

            onActivityResult(int requestCode, int resultCode,  @Nullable Intent data)
    

    before that, you shold show SecondActivity with

           startActivityForResult(intent, SECOND_CODE);
    

    so the code can be like this

            private static SECOND_CODE = 1001;
    
            Intent intent = new Intent(MainActivity.this, SecondActivity.class); 
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivityForResult(intent, SECOND_CODE);
                    
    
             @Override
             protected void onActivityResult(int requestCode, int resultCode,  @Nullable Intent data) {
                  super.onActivityResult(requestCode, resultCode, data);
                  if (requestCode == SECOND_CODE && resultCode == 
                        Activity.RESULT_OK && data != null) {
                     // you can get selected spinner item here
                  }
              }
    

    After that, when you want to show SecondActivity again

            Intent intent = new Intent(MainActivity.thisSecondActivity.class); 
            intent.putExtra("selected_spinner", /*the spinner item you got from above function*/)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivityForResult(intent, SECOND_CODE);
    

    and in SecondActivity, you can get the selected spinner item from getIntent()

            String selected_spinner = getIntent().getStringExtra("selected_spinner");
    

    Then you can find this string in Spinner and select it.