Tue. Jan 14th, 2025

Transferring data between activities in Android can be achieved using Intent. Here’s a comprehensive example of how to send and receive data between two activities.


Example: Data Transfer Between Two Activities

Step 1: Create Two Activities


MainActivity.kt

This activity sends data to SecondActivity.

package com.example.datatransferexample

import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MainScreen()
        }
    }

    @Composable
    fun MainScreen() {
        Scaffold(
            topBar = {
                TopAppBar(title = { Text("Main Activity") })
            }
        ) { padding ->
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(padding)
                    .padding(16.dp),
                verticalArrangement = Arrangement.Center
            ) {
                Button(
                    onClick = {
                        val intent = Intent(this@MainActivity, SecondActivity::class.java).apply {
                            putExtra("name", "John Doe")
                            putExtra("age", 25)
                            putExtra("isStudent", true)
                        }
                        startActivity(intent)
                    },
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Text(text = "Send Data to Second Activity")
                }
            }
        }
    }
}

SecondActivity.kt

This activity receives the data from MainActivity.

package com.example.datatransferexample

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

class SecondActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Retrieve the data sent from MainActivity
        val name = intent.getStringExtra("name") ?: "Unknown"
        val age = intent.getIntExtra("age", -1)
        val isStudent = intent.getBooleanExtra("isStudent", false)

        setContent {
            SecondScreen(name, age, isStudent)
        }
    }

    @Composable
    fun SecondScreen(name: String, age: Int, isStudent: Boolean) {
        Scaffold(
            topBar = {
                TopAppBar(title = { Text("Second Activity") })
            }
        ) { padding ->
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(padding)
                    .padding(16.dp),
                verticalArrangement = Arrangement.Center
            ) {
                Text(text = "Name: $name", style = MaterialTheme.typography.bodyLarge)
                Spacer(modifier = Modifier.height(8.dp))
                Text(text = "Age: $age", style = MaterialTheme.typography.bodyLarge)
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text = "Is Student: ${if (isStudent) "Yes" else "No"}",
                    style = MaterialTheme.typography.bodyLarge
                )
            }
        }
    }
}

Key Concepts in the Code

  1. Sending Data (MainActivity):
  • Used the Intent.putExtra() method to pass key-value pairs (e.g., name, age, isStudent).
  • Started the second activity using startActivity().
  1. Receiving Data (SecondActivity):
  • Used the intent.getStringExtra(), intent.getIntExtra(), and intent.getBooleanExtra() methods to retrieve the data.
  • Displayed the data in the UI.

Expected Output

  1. Main Activity:
  • Displays a button: “Send Data to Second Activity”.
  • Clicking the button sends data (name, age, isStudent) to SecondActivity.
  1. Second Activity:
  • Displays the transferred data:
    Name: John Doe Age: 25 Is Student: Yes

Notes:

  • Data Types Supported: String, Int, Boolean, ArrayList, Parcelable, Serializable.
  • For complex objects, use Parcelable or Serializable.

By Rajashekar

I’m (Rajashekar) a core Android developer with complimenting skills as a web developer from India. I cherish taking up complex problems and turning them into beautiful interfaces. My love for decrypting the logic and structure of coding keeps me pushing towards writing elegant and proficient code, whether it is Android, PHP, Flutter or any other platforms. You would find me involved in cuisines, reading, travelling during my leisure hours.

Leave a Reply

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