There are many ways to pass an object to a fragment. A serializable class is often used.
In this post, I want to show you my way to carry out this task. My method is just simply converting an object to a String and then bundling it.
Gson library is required to convert objects into JSON strings and vice versa. It is a Java serialization/deserialization library that can convert Java Objects into JSON and back. Gson can be downloaded here.
Install the library:
implementation 'com.google.code.gson:gson:2.8.6'
Pass an object:
val product = Product(id=1, name="HP Printer", price=1000f) val productString = Gson().toJson(product) ProductEditFragment.newInstance(productString)
Receive the product and deserialize it:
This part is for newInstance
of ProductEditFragment
.
companion object { fun newInstance(productString: String) = ProductEditFragment().apply { arguments = Bundle().apply { putString("productString", productString) } } }
In fragment’s onCreate
:
arguments?.let { productString = it.getString("productString")!! } val product = Gson().fromJson(productString, Product::class.java)