Android Share Data Between Activity and Fragment Using ViewModel

Jul 10, 2019

Parent Activity

class ParentActivity : AppCompatActivity() {    lateinit var viewModel: QuoteMakerXViewModel    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.parent)        setSupportActionBar(toolbar)        viewModel = ViewModelProviders.of(this).get(ParentViewModel::class.java)        viewModel.testMessage = "Hello"        viewModel.selectItemEvent.observe(this, Observer { event ->            Timber.d("selectItemEvent=$event")        })        viewModel.sharedLiveData.observe(this, Observer { event ->            Timber.d("sharedLiveData=$event")        })    }}

Shared ViewModel

class ParentViewModel : ViewModel() {    internal val selectItemEvent = SingleLiveEvent<String>()    internal val sharedLiveData = MutableLiveData<String>()    internal var testMessage: String? = null}

NOTE: SingleLiveEvent is used to handle UI event.

Child Fragment

class ChildAFragment : Fragment() {    override fun onCreateView(        inflater: LayoutInflater, container: ViewGroup?,        savedInstanceState: Bundle?    ): View? {        // Inflate the layout for this fragment        return inflater.inflate(R.layout.childa, container, false)    }    override fun onActivityCreated(savedInstanceState: Bundle?) {        super.onActivityCreated(savedInstanceState)        viewModel = ViewModelProviders.of(activity!!).get(ParentViewModel::class.java)        // shared message from parent        Timber.d("viewModel.testMessage=%s", viewModel.testMessage)        // send ui event back to parent        button.setOnClickListener {            viewModel.selectItemEvent.value = "ChildA button click"        }        // send data back to parent        viewModel.sharedLiveData.value = "ChildA loaded"    }}

Could create another ChildBFragment where data/event could be shared between ParentActivity - ChildAFragment - ChildBFragment

References:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.