4

I'm trying to pass arguments from my Activity to a Fragment and I'm using this code:

@Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);

        String message = getIntent().getStringExtra(Intent.EXTRA_TEXT);

        DetailActivityFragment fragment = new DetailActivityFragment();

        Bundle bundle = new Bundle();
        bundle.putString(INTENT_EXTRA, message);

        fragment.setArguments(bundle);
    }

I'm getting the value of the message variable through an Intent Extra and that works fine, so far.
Then I'm passing it as an argument to my fragment but then, when I call getArguments() from that specific Fragment it returns a null Bundle.
Does anybody have a solution to this?

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle bundle = getArguments();

        if (bundle != null && bundle.containsKey(DetailActivity.INTENT_EXTRA)) {
            forecast = bundle.getString(DetailActivity.INTENT_EXTRA);
        } else if (bundle == null) {
            Toast.makeText(getActivity(), "Error", Toast.LENGTH_LONG).show();
        }

    }

The upper method displays a Toast message "Error" when I run the app...

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Dimitris Poulopoulos
  • 1,139
  • 2
  • 15
  • 36
  • where is the FragmentTransaction ? Did you declare the Fragment in the Manifest ? – Blackbelt Jun 15 '15 at 13:55
  • 1
    you are creating different DetailActivityFragment instance somewhere (without arguments) ... and using it instead this one – Selvin Jun 15 '15 at 14:05
  • 1
    **Which** is the error you get? Can you post your **logcat**, please? Are you using any **transaction**? can you **show it** to us? – Phantômaxx Jun 15 '15 at 15:07

2 Answers2

6

The best way to use arguments with your fragment is to use the newInstance function of the fragment.Create a static method that gets your params and pass them in the fragment through the new instance function as below:

public static myFragment newInstance(String param1, String param2) {
    myFragment fragment = new myFragment ();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

And then on create set your global arguments:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}

on your main activity you will create the fragment like

myFragment __myFragment = myFragment.newInstance("test","test");

That should work

Sifis
  • 653
  • 5
  • 18
  • Should have been the accepted answer because it instantiates the fragment, sets and gets arguments through bundle state in the right way. – crakama May 08 '18 at 05:22
4

This is a correct approach

Send (in the Activity):

final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

final DetailActivityFragment  frg = new DetailActivityFragment ();
ft.replace(R.id.container, frg);

final Bundle bdl = new Bundle();
bdl.putString("yourKey", "Some Value");
frg.setArguments(bdl);

ft.commit();

Receive (in the Fragment):

final Bundle bdl = getArguments();

String str = "";
try
{
    str = bdl.getString("yourKey");
}
catch(final Exception e)
{
    // Do nothing
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • 1
    It works but at the same time it throws this exception: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference Do you know why this happens? Thanks for your answer! – Dimitris Poulopoulos Jun 16 '15 at 09:59
  • 1
    **1** - Make sure you have this import: `import android.os.Bundle;`. **2** - Don't forget to add this line `final Bundle bdl = getArguments();` or your Bundle reference would be **null**. – Phantômaxx Jun 16 '15 at 10:10
  • Yes I have them both. But it is strange. It does work and it does pass the right arguments (I see them on my results) but at the same time it says that the bundle is null. Weird stuff! – Dimitris Poulopoulos Jun 16 '15 at 11:02
  • I'm assuming that you run the receiving code in the Fragment's `onCreateView()` method. Otherwise, the Bundle might still not have been passed completely. – Phantômaxx Jun 16 '15 at 11:22