Simon
Simon

Reputation: 1731

Fragment getArguments (in onResume) returns null

I am trying to send some data from a Activity to Fragment.

I need to get the data in the onResume method of the fragment but I guess that`s not possible?

Arguments can only be received in onCreate()?

Activity:

public void someMethod() {
String someString = "test";

   Bundle bundle = new Bundle();
   bundle.putString("message", someString);
   VFragment.getInstance().setArguments(bundle);
}

Fragment:

 public class VFragment extends BaseFragment {

    public static VFragment getInstance() {
            return VFragment_.builder().build();
        }

        public VFragment() {
        }

    @Override
    public void onResume() {
        super.onResume();
        String receive = getArguments().getString("message");
        Log.v(TAG, receive); // NULL
    }
}

Upvotes: 2

Views: 1125

Answers (3)

Simon
Simon

Reputation: 1731

First of all thanks for everyone who responded and tried to help. My mistake that I forgot to mention that I use Android Annotations.

The proper way to do this with annotations is:

Set a FragmentArg in your 'targetFragment':

@FragmentArg
String receiveA;

Make the receiver method of the Fragment:

public static VFragment getInstance(String message) {
        // Do something with String message
        return VFragment_.builder().receiveA(message).build();
    }

Make the call in the 'source' Activity to send the data:

VFragment.getInstance("This is a test");

Result in targetFragment:

@Override
public void onResume() {
    super.onResume();
    Log.v(TAG, message); // Prints 'This is a test'
}

Upvotes: 0

Catarina Ferreira
Catarina Ferreira

Reputation: 1854

Here's an example of my code:

  • Fragment 1

                        reservation_main_data reservation_main_data = new reservation_main_data();
                        Bundle bundle = new Bundle();
                        bundle.putCharSequence(bundle_string, txt_results_experience.getText()); //Sending the experience name clicked to another fragment
                        reservation_main_data.setArguments(bundle);
                        FragmentManager manager = getActivity().getSupportFragmentManager();
                        manager.beginTransaction().replace(R.id.framelayout_secundary, reservation_main_data, reservation_main_data.getTag()).commit();
    
  • Fragment 2

    Bundle bundle = this.getArguments();

if (bundle != null) { CharSequence myInt = bundle.getCharSequence(bundle_string); txt_results_experience.setText(String.valueOf(myInt)); }

Upvotes: 0

Paresh
Paresh

Reputation: 6857

Alright I don't know what is builder() and build but this is good practice...

public static VFragment newInstance(String text) {
        Bundle b = new Bundle();
        b.putExtrs("message", text)
        VFragment mF = new VFragment();
        mF.setArguments(b);
        return mF;
    }

Try this out. Reference

Upvotes: 1

Related Questions