4

How do you pass a data from activity to fragment that's already active? I can transfer using a bundle but the only way I can get it is using createView on that fragment but my problem is it is already created. Is there anyway that I can pass data from activity to fragment and then call that data without using onCreateView

I tried this link to get what I needed but the data is not accessible due to static

Michael Dodd
  • 10,102
  • 12
  • 51
  • 64
myown email
  • 139
  • 1
  • 10
  • via callback interface, look here [https://stackoverflow.com/questions/14247954/communicating-between-a-fragment-and-an-activity-best-practices](https://stackoverflow.com/questions/14247954/communicating-between-a-fragment-and-an-activity-best-practices) – Vadim Eksler Aug 08 '18 at 10:59
  • You should look at event bus in my answer. The easiest solution, I found ever. – Khemraj Sharma Aug 08 '18 at 11:48
  • @Khemraj sure currently reading on it and also plus 1 – myown email Aug 08 '18 at 11:51

3 Answers3

3

There can be multiple ways

  • Get Fragment instance by using findFragmentById as @Belbahar Raouf showed.
  • Use BroadcastReceiver to send data between Activity, Fragment or Service. It works everywhere. But it can be little lengthy.
  • You can use EventBus, a great invention from GreenBot. Just one line to pass data.

    EventBus.getDefault().post(new MessageEvent());

See Event bus documentation for implementation.

Make a model class that will be passed MessageEvent.java.

public static class MessageEvent { /* Additional fields if needed */ }

Subscribe your listener in Fragment.

@Subscribe(threadMode = ThreadMode.MAIN)  
public void onMessageEvent(MessageEvent event) {/* Do something */};

Register & Unregister event bus with Fragment Lifecycle.

@Override
 public void onStart() {
     super.onStart();
     EventBus.getDefault().register(this);
 }

 @Override
 public void onStop() {
     super.onStop();
     EventBus.getDefault().unregister(this);
 }

From your Activity, just fire event, this will be received by Fragment.

EventBus.getDefault().post(new MessageEvent());

Before that add dependency to your gradle.

implementation 'org.greenrobot:eventbus:3.1.1'

Best thing of EventBus-

It works in Activity, Fragment & Services. You need not to make multiple broadcast receiver with multiple intent types. Just post event in one line code.

I also use EventBus for ease of use.

Khemraj Sharma
  • 57,232
  • 27
  • 203
  • 212
2

If view is already created then onCreateview will not call so you can pass data via BroadcastReceiver

 BroadcastReceiver receiverUpdateDownload = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //Getdata from intent
        }
    };

Regester your BroadcastReceiver in onCreateView

IntentFilter filter = new IntentFilter("STRING_ID_FOR_BRODCAST");
getActivity().registerReceiver(receiverUpdateDownload, filter);

unregister your Receiver at onStop

@Override
public void onStop() {
    super.onStop();
    if (receiverUpdateDownload != null) {
        try {
            getActivity().unregisterReceiver(receiverUpdateDownload);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Call your brodcast from acttvity

 Intent intent = new Intent("STRING_ID_FOR_BRODCAST");
 intent.putExtra("key","value");
 sendBroadcast(intent);
PriyankVadariya
  • 809
  • 9
  • 14
0

According to documentation :

The host activity can deliver messages to a fragment by capturing the Fragment instance with findFragmentById(), then directly call the fragment's public methods.

Example (declare this in your activity):

ArticleFragment articleFrag = (ArticleFragment)
           getSupportFragmentManager().findFragmentById(R.id.article_fragment);

        if (articleFrag != null) {
            // If article frag is available
            // Call a method in the ArticleFragment to update its content
            articleFrag.updateArticleView(position);
        }

And in your fragment implement the method that will do the trick.

Belbahar Raouf
  • 760
  • 1
  • 4
  • 17