Send Data from Activity to Fragment in Android

Frequently used code samples and tutorials
vivekkalady
Site Admin
Posts: 35
Joined: Tue Nov 18, 2014 2:39 pm

Send Data from Activity to Fragment in Android

Postby vivekkalady » Mon Nov 24, 2014 3:41 pm

We can send data to a fragment by using Bundle

First Method

eg:-

Code: Select all

Bundle bundle = new Bundle();
bundle.putString("Key", "StringValue");
NewFragment fragobj = new NewFragment();
fragobj.setArguments(bundle);


Then in Fragment we can take the data as
Fragment onCreateView method:

Code: Select all

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
    String strtext = getArguments().getString("Key");   
    return inflater.inflate(R.layout.fragment, container, false);
}



Second Method :

you can create any public function in MainActivity.java which is the parent Activity of the fragment

eg:-

Code: Select all

public void String getData()
{
     return "Data from Activity";
}



Then in Fragment, you can Cast the MainActitivy to an object like this


Code: Select all

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
    MainActivity activity = (MainActivity)getActivity();
    String Data = activity.getData();
    return inflater.inflate(R.layout.fragment, container, false);
}



Third Method For Sending Complex Data

for complex objects you need to implement Serializable. For example, for the simple object:

Code: Select all

public class MyClass implements Serializable {
    private static final long serialVersionUID = -2163051469151804394L;
    private int id;
    private String created;
}


In you FromFragment:

Code: Select all

Bundle args = new Bundle();
args.putSerializable(TAG_MY_CLASS, myClass);
Fragment toFragment = new ToFragment();
toFragment.setArguments(args);
getFragmentManager()
    .beginTransaction()
    .replace(R.id.body, toFragment, TAG_TO_FRAGMENT)
    .addToBackStack(TAG_TO_FRAGMENT).commit();


in your ToFragment:

Code: Select all

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

    Bundle args = getArguments();
    MyClass myClass = (MyClass) args
        .getSerializable(TAG_MY_CLASS);

...
}

Return to “Tutorials & Examples”

Who is online

Users browsing this forum: No registered users and 1 guest

cron