How to Pass an Object to a Fragment in Android

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)

Leave a Comment

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


Scroll to Top

By continuing to use the site, you agree to the use of cookies. 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