Introduction
This article explains how to switch among Activities and send data in Android. Android Studio is used to create the sample.
This application will send data to another activity when you enter the data in the previous activity on a button click. For this, you need to create a Java class named MainActivity where you will use two textviews, two edittexts, and a button. So you will enter the data that you want to in another activity on a button click.
So to data you need to use an Intent. Intents are used to data and perform switching among activities. So to use Intent methods you will create the object of the intent and the context and activity on which you want to switch as a parameter. Now to transfer data you will call the putExtra() method that contains both the parameters of the string type. the data as a parameter in the putExtra() method and the intent object as a parameter in the startActivity() method.
Now create another Java class named Second that holds the sent data by the activity. Create the object of the intent and call the getStringExtra() method that will return the data in string formated by the MainActivity. Now set the data in textview by calling the setText method provided by the TextView class.
Step 1
Create a project like this:
"File" -> "New Project" -> "Android Application"
Step 2
Create an XML file named actvitymain.xml as in the following:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:background="#FFC6A9"
- >
- <TextView android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="Enter Name: "/>
- <EditText android:id="@+id/editText1"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_marginBottom="10dip"/>
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="Enter Age: "
- />
- <EditText android:id="@+id/editText2"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_marginBottom="10dip"
- android:inputType="number"/>
-
- <Button android:id="@+id/sendButton"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="Send"
- android:layout_marginTop="15dip"/>
- </LinearLayout>