I would like to create a Fragment, and have a complex type (MyClass) as its parameter.
The guide does not really mention it. I was able to find some examples with Bundle
, but those only contain simple parameters, like String
and Integer
.
2 Answers
You can create a static method named getInstance()
or createInstance()
or what ever you like for creating Fragment with some value
Java Version:
public static MyFragment newInstance(int arg) {
Bundle args = new Bundle();
args.putInt("ARG", arg);
MyFragment fragment = new MyFragment();
fragment.setArguments(args);
return fragment;
}
Kotlin Version:
class MyFragment : Fragment() {
companion object {
fun newInstance(arg: Int): MyFragment {
val args = Bundle()
args.putInt("ARG", arg)
val fragment = MyFragment()
fragment.arguments = args
return fragment
}
}
}
I was able to find some examples with Bundle, but those only contain simple parameters, like String and Integer.
To pass custom object in Bundle
you can use make your class Parcelable
or Serializable
. For Parcelable you can use putParcelable
method to store your object in Bundle.
For Parcelable
and Serializable
in Android check this thread.
You will find some plugin in Android Studio that will auto generate Parcelable
implementation code for your class
Another approach is convert your object to String using Gson and put that String in Bundle.
For Gson
check this post

- 5,729
- 3
- 31
- 50
Your best bet is probably serializing the complex class and deserializing it again in the fragment.
So something like
bundle.putString("object_key", gson.toJson(yourClassInstance));
And then deserialize it with
Type yourClassType = new TypeToken<YourClass>() {}.getType();
YourClass yourClassInstance = gson.fromJson(bundle.getString("object_key"), yourClassType);
or, if your class isn't generic:
gson.fromJson(bundle.getString("object_key"), YourClass.class);
For more information, see the Gson docs

- 1
- 1