0

Like I said in the title, I want to send data from an activity to a fragment, but the fragment needs to use the data received when it is created, not after a button is pressed like usual. The activity that puts the values in the bundle is the one before the activity that calls the fragment, so that the bundle is already filled when the fragment is called.

From my research the best way to do this is using a bundle, but when I do String data = bundle.getString("value"), I get a null pointer exception, meaning the bundle is empty, but I already checked and the values are there. How do I fix this?

1 Answers1

0

Better to use Eventbus for passing data activity to fragment, which is simple and concise.

1- Register/unregister to an event bus

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

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

2- Define an event class

public class Message{
    public final String message;

    public Message(String message){
        this.message = message;
    }
}

3- Post this event in anywhere in your application

EventBus.getDefault().post(new Message("hello world"));

4- Subscribe to that event to receive it in your Fragment

@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessage(Message event){
    mytextview.setText(event.message);
}

More details: https://github.com/greenrobot/EventBus

How to pass data between fragments

https://androidwave.com/fragment-communication-using-eventbus/

Horrorgoogle
  • 7,858
  • 11
  • 48
  • 81