How to Pass an Object to a Fragment in Android

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)

Leave a Comment

Your email address will not be published. Required fields are marked *

We care about your privacy and data security. Google serves cookies to analyse traffic and show ads on this site. By using this site you agree to these cookies being set. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close