There are many ways to pass an object to a fragment. 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 String then bundling it.
Gson library is required to convert object into Json string and vice versa. It is a Java serialization/deserialization library which can convert Java Objects into JSON and back. Gson can be download 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)