简体   繁体   中英

Update data fragment from another activity

It's seem to be easily but I cannot find solution although i have checked at: How to update Android fragment from activity? How to change fragment's textView's text from activity

My problem is:

I have 4 class:

  • MainActivity.java
  • HistoryFragment.java
  • ConversationDialog.java
  • CallActivity.java

In MainActivity.java, It content 2 Fragment includes HistoryFragment and ContactFragment. From HistoryFragment, I call ConversationDialog to show dialog, input to dialog and press OK to open CallActivity.

Now, I want when I press back from CallActivity, I must update HistoryFragment with new data.

But after research, I cannot do it.

Please help me to do this.

The onResume() function of the MainActivity will be get called when you are pressing back button from CallActivity. Here the logic goes.

Do the following steps,

1.Implement a public method(ie, updateContent()) in HistoryFragment to update your content.

2.Get the HistoryFragment instance from onResume() of MainActivity

FragmentManager fragmentManager = activity.getSupportFragmentManager();
HistoryFragment aFragment=fragmentManager.findFragmentByTag("Place the History fragment TAG here which you have used to load before");

3.After getting the instance, call the relevent method through instance.

aFragment.updateContent()

When starting the CallActivity use startActivityForResults like:

Intent intent = new Intent(this,  CallActivity.class);
startActivityForResult(intent, 1);

Where 1 is the request code that will be used later to get back the data you are requesting.

Then in your onBackPress function in Call Activity

Intent intent = new Intent();
intent.putExtra("id","value")
setResult(RESULT_OK, intent);        
finish();

Then do this to get your data in the previous Activity

public void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
     if(resultCode == RESULT_OK){
      String stredittext=data.getStringExtra("id");
  }
} 

Use the "id" is the identifier of your value which is "value" .I think now you can easily do the rest of adding your data to the history fragment using public variables.

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