skip to Main Content

I have two Activities, Activity 1 has 2 EditText, it takes input and goes to the next activity. Now if I go back to the previous activity and enter different input in EditText then it doesn’t get updated in the next activity. It still takes the earlier input.

2

Answers


  1. you have multi ways that you can do:

    1. when you back to the first activity, finish the second activity. and open it again.

    2. update your UI with new data, in the onResume method of the second activity. you can store data in a singleton class.

    Login or Signup to reply.
  2. The first answer is useful. But if you want to change the data live when the user types anything, then you can follow this example:

    Make the public interface

    public interface TextChangeInterface {
      void onValueChanged(String str);
    }
    

    Implement it in SecondActivity

    public class SecondActivity extends AppCompatActivity implements TextChangeInterface {
    }
    

    Override the interface method, then change the text value in it.

    @Override
    public void onValueChanged(String str) {
      textView.setText(str);
    }
    

    Then initialize & call the interface method from FirstActivity when user changes the edittext text like this :

    TextChangeInterface textChangeInterface;
    

    In onCreate()

    textChangeInterface = new SecondActivity();
    
    editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    
            }
    
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    
            }
    
            @Override
            public void afterTextChanged(Editable editable) {
              if (textChangeInterface != null) {
                if (!TextUtils.isEmpty(edittext.getText())) {
                  textChangeInterface.onValueChanges(edittext.getText().toString());
                }
              }
            }
        });
    

    And that’s it!

    NOTE : You must check if the interface is not null as the first time you run the app, the second activity won’t get created first, so it can create nulPointerException when initializing the interface, then check if the edittext value is not null & then get Text from edittext and pass it into interface.

    So the data will be updated immediately when user types any value in edittext.

    If you want to save the data to SecondActivity when user presses the save button, then you can go with the First answer. It’s also right 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search