1

My Problem is:

I have 3 classes:

  • MainActivity.java
  • ContactFragment.java
  • AddNewContactActivity.java

In MainActivity, it's content ContactFragment. From MainActivity, I click on Add Button to go to AddNewContactActivity

I want When I click on Save Button in AddNewContactActivity and go back to MainActivity, I must update ContactFragment with new data

How can I do this? Thanks you so much

Jason Momoa
  • 123
  • 8

2 Answers2

0

When starting AddNewContactActivity start it with startActivityForResult. AddNewContactActivity can pass back result code representing success and cancellation. When the starting activity receives success result code it can reload/ refresh its content.

Ref: https://www.javatpoint.com/android-startactivityforresult-example

Vihaan Verma
  • 12,815
  • 19
  • 97
  • 126
0

Use startActivityForResult.

private static int final ADD_CONTACT_CODE = 1;

// MainActivity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ADD_CONTACT_CODE && resultCode == RESULT_OK) {
            // data is the contactIntent you set in AddNewContactActivity
            // update your fragment here with that data
        }

    }

// addContactButton in MainActivity
onClick {
    startActivityForResult(addNewContactIntent, ADD_CONTACT_CODE);
}

// AddNewContactActivity
// call this when you're finish adding contact
void finishAddContact() {
    Intent contactIntent = Intent();

    // add your added contact here
    contactIntent.putExtra("added contact", addedContact)

    setResult(RESULT_OK, contactIntent);
    finishActivity(ADD_CONTACT_CODE); // this will close this activity returning to the MainActivity and calling its onActivityResult
}

Israel dela Cruz
  • 794
  • 1
  • 5
  • 11