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);
}