Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass the data in between activity to fragment using intent in Android

I can store the value in one variable now I want pass that variable into fragment.

With the following code I am able to load fragments.

   public class AndroidListFragmentActivity extends Activity {
Fragment2 f2;
public static String itemname;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.apetiserfragement);
    itemname=getIntent().getStringExtra("itemname");
    Bundle args=new Bundle();
    args.putString("itemname", itemname);
    f2=new Fragment2();
    f2.setArguments(args);

}
}

(Here I load fragment using XML page) itemname

The output is split into into 2 windows one for extend for listfragment(for listview). One for fragments

Fragment2.xml

    public class Fragment2 extends Fragment {
String itemname;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub

    System.out.println(getArguments().getString("itemname"));

    return inflater.inflate(R.layout.fragment2, container, false);
}

@Override
public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

}

  }

AndroidListFragmentActivity in this class itemname I want pass Fragment2.class.

like image 450
naveen Avatar asked Oct 07 '22 14:10

naveen


1 Answers

Use the bundle provided in one of the fragment constructors, and then you should be able to retrieve the Bundle by doing getArguments() right where you want to in onCreateView()

Example:

YourFragment.instantiate(context,"fragName",yourBundleWithValue);

Then, in your fragment:

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

    getArguments().getStringValue("name"); //Returns your string value

    return inflater.inflate(R.layout.fragment2, container, false);
}
like image 96
hwrdprkns Avatar answered Oct 16 '22 03:10

hwrdprkns