Passing Data between Mobile Screens in Android

Passing Data between Mobile Screens in Android

In this article, we will learn how to pass data between different mobile screens in Android.

  1. Sharing Data b/w Activities

  2. Sending Data from Activity to Fragment

  3. Sending Data from Fragment to Activity

  4. Sharing Data b/w Fragments


Sharing Data b/w Activities :

As discussed in the Intent Article, the data can be passed from one activity to another using the intent object, which is used to communicate between components.

Sending Data with Intent

//SENDING DATA -> 
intent.putExtra("name",username) 
intent.putExtra("age",userage)
//first parameter is the tag that helps us identify data
//second parameter is the data that needs to be passed

//RECEIVING DATA ->
intent.getStringExtra(name)
intent.getIntExtra(age,0)
//first parameter is the tag that helps us identify data
//second parameter is the default value

Sending Data from Activity to Fragment :

As discussed in the Fragment Article, the data can be passed from one activity to another using the bundle object.

Sending Data with Bundle

//SENDING DATA ->
//needs to be executed before committing the fragment transaction
val bundle = Bundle() //creating an object of Bundle class
bundle.putInt("position",position) //passing the tag & data 
fragment.arguments = bundle //binding the bundle to the fragment

//RECEIVING DATA ->
arguments?.getInt("position",0) //tag & default value is passed

Sending Data from Fragment to Activity :

As discussed in the Fragment Article, the data can be passed from one activity to another using the object of the corresponding activity.

Sending Data with Activity Object

//SENDING DATA -> 
val mainActivity : MainActivity = activity as MainActivity
//creating the object of MainActivity
mainActivity.gettingData(userName,userAge)
//calling the function on the object of mainActivity
//passing the data as parameters 

//(activity as MainActivity).gettingData(userName,userAge)

//RECEIVING DATA ->
//user-defined function of our activity class
fun gettingData(userName : String, userAge : Int){
//used to receive data from fragment
    val name : String = "Name: $userName"
    val age : String = "Age: $userAge"
}

Sharing Data b/w Fragments :

Sharing Data b/w Fragments can also be achieved using the Bundle Class.

//SENDING DATA -> 
val bundle = Bundle() 
bundle.putInt("name",username) //passing the tag & data 
val secondFragment = SecondFragment()
secondFragment.arguments = bundle
//... commit transaction

//RECEIVING DATA ->
val name : String = arguments?.getString("name").toString()