Tutorial details

Android beginner tutorial: Part 58 - Send and receive data between Activities | App Code for Sale | Preview

Android beginner tutorial: Part 58 - Send and receive data between Activities | Android Tutorial

How to transfer data between two Activities

Overview PAGE TOP

In this tutorial we'll learn how to transfer data between two Activities.

We are going to have two activities - MainActivity and SecondActivity. I've already covered how to create secondary Activities in the tutorial about Intents. I explained how to do that in detail in that tutorial, so if you followed my tutorials you should be able to do that. A reminder: add an Activity in the Manifest XML file and add a SecondActivity.java class and an activity_second.xml layout.

The main activity is going to have a button that opens a new Activity. However, it launches it with an intention to receive a result. This is done using a startActivityForResult() method. By doing it that way we tell our main activity to expect a result from the Activity we're launching. In the second activity we'll have an EditText input and a button. When the button is pressed, the data in the text field is sent back to the main activity and the second activity is closed.

When the main activity receives the message, it displays it in a toast.

Let's see how we are going to do this. Firstly, go to activity_main.xml layout and add a button:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="32sp"
        android:text="First Activity"
        />

    <Button android:id="@+id/goButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Launch Second Activity"
        />

</LinearLayout>

In MainActivity.java declare an ID for the request:

private static final int IDM_TEST = 101;

Use it when you call startActivityForResult() in the click event handler of the button:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final Button btn = (Button)findViewById(R.id.goButton);
btn.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(getApplicationContext(), SecondActivity.class);
startActivityForResult(intent, IDM_TEST);
}
});
}

The request is sent, but what about receiving the results?

Create a function onActivityResult(). Call its superclass and then check if resultCode parameter equals RESULT_OK. That means we've received a result as expected.

Inside the if...statement declare an "extras" variable, which is a Bundle type object and gets its values from data.getExtras().

Then we check if requestCode parameter's value equals IDM_TEST (the id we passed when requesting the result), and if so, toast the results using the extras object:

protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
Bundle extras = data.getExtras();
// handle results
if(requestCode == IDM_TEST){
Toast toast = Toast.makeText(MainActivity.this, extras.getString("UserText"), Toast.LENGTH_SHORT);
toast.show();
}
}
}

Full MainActivity.java code:

package com.kircode.codeforfood_test;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity{

private static final int IDM_TEST = 101;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final Button btn = (Button)findViewById(R.id.goButton);
btn.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(getApplicationContext(), SecondActivity.class);
startActivityForResult(intent, IDM_TEST);
}
});
}

protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
Bundle extras = data.getExtras();
// handle results
if(requestCode == IDM_TEST){
Toast toast = Toast.makeText(MainActivity.this, extras.getString("UserText"), Toast.LENGTH_SHORT);
toast.show();
}
}
}

}

The activity_second.xml layout has an EditText object and a Button:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="32sp"
        android:text="Second Activity"
        />

    <EditText android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Write something here..."
        android:id="@+id/editText"
        />

    <Button android:id="@+id/backButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="OK"
        />

</LinearLayout>

In SecondActivity.java class, we only need to handle the button. When it is clicked, we create an intent and use a method called setResult(). To pass the values to the parent activity we can use the putExtra() method of the intent. It has 2 parameters - name and value.

package com.kircode.codeforfood_test;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class SecondActivity extends Activity{


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);

final Button btn = (Button)findViewById(R.id.backButton);
btn.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
EditText text = (EditText)findViewById(R.id.editText);

Intent intent = new Intent();
intent.putExtra("UserText", text.getText().toString());
setResult(RESULT_OK, intent);
finish();
}
});
}

}

That's all! Now you can go to the second activity from your main one, enter some text, return to the main activity using the button and see the main activity display the data received from the second one.

Thanks for reading!

Reference PAGE TOP

http://kirill-poletaev.blogspot.it/2013/01/android-beginner-tutorial-part-58-send.html

0 Comments Leave a comment

Please login in order to leave a comment.

Newest first
!

Sign-in to your Chupamobile Account.

The Easiest way to Launch your next App or Game.

Join Chupamobile and get instant access to thousands of ready made App and Game Templates.

Creating an account means you’re okay with Chupamobile’s Terms of Service and Privacy Policy.