0

How do i pass a value from an Activity to a Fragment?

I understand that i can use setArgument in my Activity and getArgument in Fragment. But i did it with no luck. The value still returns as null.


Activity

public class nfc_activity extends Activity {
    private ImageView mCardView;
    MyFragmentA f2;
    public static String itemname;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         Button goButton = (Button)findViewById(R.id.go);
            goButton.setOnClickListener(mGoListener);


        }

       private OnClickListener mGoListener = new OnClickListener()
        {
            public void onClick(View v)
            {
                // Here we start up the main entry point of our redirection
                // example.
                String itemname ="1";

                  MyFragmentA fragment = new MyFragmentA();
                Bundle bundle2 = new Bundle();
                bundle2.putString("key", itemname);
                fragment.setArguments(bundle2);

            }
        };

}

Fragment

public class MyFragmentA extends Fragment {



 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState) {

  Bundle bundle = this.getArguments();
  if (bundle != null) {
      String hello = bundle.getString("key", defaultValue);
      System.out.println(hello);
  }
prolink007
  • 33,872
  • 24
  • 117
  • 185

2 Answers2

0

Your code doesn't show how your fragment is attached to the activity, but you have to make sure the arguments are set on the fragment before you attach it for them to be available in onCreateView.

Majix
  • 1,702
  • 1
  • 16
  • 8
  • something like : Fragment fragment = (Fragment)getFragmentManager().findFragmentById(R.id.pager); Bundle bundle2 = new Bundle(); bundle2.putString("key", itemname); fragment.setArguments(bundle2); i got nullpointerexception from using this. please help – user1559674 Aug 01 '12 at 12:49
0

Have you tried using a Tag to identify your Fragment and findFragmentByTag to retrieve it? It seems to me cleaner than using findFragmentById which actually look for the id of the inflated XML layout or the id of the container layout!

type-a1pha
  • 1,891
  • 13
  • 19