PASSING DATA BETWEEN ACTIVITIES USING INTENT
PASSING DATA BETWEEN ACTIVITIES USING INTENT
In Android, it is common to pass data from one activity to another using an intent. An intent is a messaging object that is used to communicate between different components of an Android application, such as activities, services, and broadcast receivers. In this guide, we will explore how to pass data from one activity to another using intent method in Android.
Basic Steps
The following are the basic steps involved in passing data from one activity to another using intent method in Android:
- Create an Intent object in the source activity.
- Put extra data in the intent.
- Start the destination activity.
- Retrieve the extra data in the destination activity.
CREATE NEW PROJECT IN ANDROID
start a new project in Android Studio, follow these steps. Alternatively you can visit our previous article to see how you can create a new project in android create first project in android
- Open Android Studio
- Click on “Start a new Android Studio project” or select “File” -> “New” -> “New Project”
- Select a project template (e.g. Empty Activity) and click “Next”
- Configure the project name, package name, save location, and other settings as needed.
- Click “Finish” to create the project.
As we will pass data from MainActivity into the second activity, therefore you should create second activity. To create a second activity in Android Studio, follow these steps:
- Right-click on your project in the project explorer and select “New” -> “Activity” -> “Empty Activity”
- In the “Configure Activity” dialog box, set the activity name, layout name, and other settings as required.
- Click “Finish” to create the new activity. This will create a new Java class file and a corresponding layout XML file.
Creating an Intent Object
To pass data from one activity to another using intent method, we first need to create an intent object in the source activity. An intent object is created using the Intent class constructor. The constructor takes two arguments – the context of the source activity and the class of the destination activity. The context of the source activity can be obtained using the this keyword, and the class of the destination activity can be obtained using the .class syntax.
For example, if we have a MainActivity class and a SecondActivity class, we can create an intent object to start the SecondActivity by clicking a button as explained below.
So, lets first design the layout of our MainActivlty XML:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Next" android:layout_marginLeft="21dp" android:layout_marginBottom="11dp" android:id="@+id/btnNext"/> </LinearLayout>
Putting Extra Data in the Intent
Once we create an intent object, we can add extra data to it using the putExtra() method. The putExtra() method takes two arguments – a key and a value. The key is a string that is used to identify the data, and the value can be any data type that can be serialized, such as a string, integer, boolean, or custom object.
For example, to pass a string value from the MainActivity to the SecondActivity, we can use the following code:
Once we have added extra data to the intent, we can start the destination activity using the startActivity() method. The startActivity() method takes the intent object as an argument and starts the activity specified by the intent.
Now go to MainActivit.java class and code it as below:
package com.panrum.passingdatasecondactivity; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btnNext; btnNext=findViewById(R.id.btnNext); btnNext.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent myIntent; myIntent=new Intent(MainActivity.this,SecondActivity.class); String message = "Hello, SecondActivity!"; myIntent.putExtra("message_key", message); startActivity(myIntent); } }); } }
Look here, When the SecondActivity is started, it can retrieve the extra data passed from the MainActivity using the getIntent() method. The getIntent() method returns the intent that started the activity.
For example, to retrieve the string value passed from the MainActivity, we can use the following code in the SecondActivity:
package com.panrum.passingdatasecondactivity; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.widget.Toast; public class SecondActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); Intent intent = getIntent(); String message = intent.getStringExtra("message_key"); Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show(); } }
Examples
Now we will give you some more examples of passing data from one activity to another using intent method in Android. Try them yourself.
Passing a string value from MainActivity to SecondActivity:
In MainActivity:
String message = "Hello from MainActivity!"; Intent myintent = new Intent(MainActivity.this, SecondActivity.class); myintent.putExtra("MESSAGE", message); startActivity(myintent);
In SecondActivity:
Intent intent = getIntent(); String message = intent.getStringExtra("MESSAGE");
Passing an integer value from MainActivity to SecondActivity:
In MainActivity:
int value = 123; Intent myintent = new Intent(MainActivity.this, SecondActivity.class); myintent.putExtra("VALUE", value); startActivity(myintent);
In SecondActivity:
Intent intent = getIntent(); int value = intent.getIntExtra("VALUE", 0);
Passing an object from MainActivity to SecondActivity using Parcelable:
Assuming you have a custom class named Person that implements the Parcelable interface:
Person person = new Person("Khalil ur Rahman", "Atiq ur Rahman"); Intent myintent = new Intent(MainActivity.this, SecondActivity.class); myintent.putExtra("PERSON", person); startActivity(myintent);
In SecondActivity:
Intent intent = getIntent(); Person person = intent.getParcelableExtra("PERSON");
Passing data using Using Global Variables
Using global variables to pass data between activities in Android is generally not recommended as it can lead to unexpected behavior and bugs. It’s better to use the Intent method or other recommended ways of data sharing such as a database or SharedPreferences.
However, if you still want to use global variables to pass data between activities, here’s an example.
Creating a global variable in MainActivity to store a string value:
public class MainActivity extends AppCompatActivity { public static String message = "Hello from MainActivity!"; // ... }
Accessing the global variable from SecondActivity:
public class SecondActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); String message = MainActivity.message; // ... } }
Again, using global variables to pass data between activities is not recommended as it can lead to unexpected behavior and bugs. It’s better to use the Intent method or other recommended ways of data sharing such as a database or SharedPreferences.
passing data using Database sharing
Creating a database and inserting data in MainActivity:
Assuming you have a database helper class named MyDatabaseHelper:
public class MainActivity extends AppCompatActivity { private MyDatabaseHelper dbHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); dbHelper = new MyDatabaseHelper(this); SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("message", "Hello from MainActivity!"); db.insert("messages", null, values); } }
2. Retrieving data from the database in SecondActivity:
public class SecondActivity extends AppCompatActivity { private MyDatabaseHelper dbHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); dbHelper = new MyDatabaseHelper(this); SQLiteDatabase db = dbHelper.getReadableDatabase(); String[] projection = {"message"}; Cursor cursor = db.query("messages", projection, null, null, null, null, null); if (cursor.moveToNext()) { String message = cursor.getString(cursor.getColumnIndexOrThrow("message")); // do something with message } cursor.close(); } }
passing data Using SharedPreferences
Storing a string value in SharedPreferences in MainActivity:
public class MainActivity extends AppCompatActivity { private SharedPreferences sharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sharedPreferences = getSharedPreferences("my_prefs", MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("message", "Hello from MainActivity!"); editor.apply(); } }
Retrieving the string value from SharedPreferences in SecondActivity:
public class SecondActivity extends AppCompatActivity { private SharedPreferences sharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); sharedPreferences = getSharedPreferences("my_prefs", MODE_PRIVATE); String message = sharedPreferences.getString("message", ""); // do something with message } }
CONCLUSION:
In Android, there are multiple ways to pass data between activities, including Intent, global variables, databases, and SharedPreferences.
Using Intents is the most common and recommended way to pass data between activities, as it’s a built-in feature of the Android framework and is designed specifically for this purpose. You can pass data of various types such as strings, integers, booleans, and objects, and it’s also possible to pass data both ways between activities.
Global variables are not recommended for passing data between activities, as they can lead to unexpected behavior and bugs, but they can still be used if necessary. Global variables are created in one activity and accessed in another, but you need to be careful to ensure they are updated correctly.
Using databases and SharedPreferences are also valid ways to pass data between activities, but they are typically used for storing and retrieving data across the entire app, rather than just between two activities.
Overall, it’s important to choose the right method for passing data between activities based on your specific use case and requirements. Each method has its advantages and disadvantages, and the best approach depends on factors such as the type and amount of data you need to pass, the frequency of data exchange, and the level of security and persistence required.