How to transfer some data to another Fragment?
How to transfer some data to another Fragment
likewise it was done with extras
for intents
?
Use a Bundle
. Here's an example:
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);
Bundle has put methods for lots of data types. See this
Then in your Fragment
, retrieve the data (e.g. in onCreate()
method) with:
Bundle bundle = this.getArguments();
if (bundle != null) {
int myInt = bundle.getInt(key, defaultValue);
}
To extend the previous answer even more, like Ankit was saying, for complex objects you need to implement Serializable. For example, for the simple object:
public class MyClass implements Serializable {
private static final long serialVersionUID = -2163051469151804394L;
private int id;
private String created;
}
In your FromFragment:
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:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle args = getArguments();
MyClass myClass = (MyClass) args
.getSerializable(TAG_MY_CLASS);
getArguments() is returning null because "Its doesn't get anything"
Try this code to handle this situation
if(getArguments()!=null)
{
int myInt = getArguments().getInt(key, defaultValue);
}
Complete code of passing data using fragment to fragment
Fragment fragment = new Fragment(); // replace your custom fragment class
Bundle bundle = new Bundle();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
bundle.putString("key","value"); // use as per your need
fragment.setArguments(bundle);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(viewID,fragment);
fragmentTransaction.commit();
In custom fragment class
Bundle mBundle = new Bundle();
mBundle = getArguments();
mBundle.getString(key); // key must be same which was given in first fragment
Just to extend previous answers - it could help someone. If your getArguments()
returns null
, put it to onCreate()
method and not to constructor of your fragment:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int index = getArguments().getInt("index");
}