How to transfer data between two Activities in Android

In this android development tutorial for beginners, we will explore how to transfer string value from one activity to the other using a button click. This is a common situation in android application development. For beginner android developers who are trying their hand in android will find this post interesting.

Our case study in this tutorial is to develop a simple android app with an input field where users can input a string and on a button and the entered name will be display on a new activity page.

If you have never done anything with android or you have no basic understanding of android development, I will suggest you read my tutorial on beginners android development.

Let’s start with firing up our android IDE. I will be using Eclipse for this tutorial but you are free to use whatever android IDE you referred.

Once you have started up your IDE, create a new android project called Testing.

Select the min required SDK as API 8 and targeted SDK as API 19.

Click the next button

Continue with the default setting until the finish button is active.

Click on the finish button to generate your android application project structure

Now when you go to the src folder, you will see that a MainActivity java file has been generated for us. We are going to create our controls in the generated activity_main.xml file. Double click on the file which is located at layout folder under the res folder.

Go to the design view and drag and drop an EditText and Button controls on the file. You can also use the code section. If you don’t want do it yourself you can copy and paste the following xml code on the xml file.

<RelativeLayout 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"

    tools:context="com.example.test.MainActivity" >

    <EditText

        android:id="@+id/name_input"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_alignParentTop="true"

        android:layout_centerHorizontal="true"

        android:layout_marginTop="70dp"

        android:layout_marginLeft="10dp"

        android:layout_marginRight="10dp"

        android:inputType="text"

        android:ems="10" >

        <requestFocus />

    </EditText>

    <Button

        android:id="@+id/submit_button"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_below="@+id/name_input"

        android:layout_centerHorizontal="true"

        android:layout_marginTop="72dp"

        android:text="@string/button_name" />

</RelativeLayout>

We will move over to the MainActivity.java file to code what will happen when a user adds his or her name and click on the submit button.

We will follow the steps listed below.

  1. We will get the instances of the view controls we have created in the xml file
  2. We will attach a click event listener to our button so that whenever someone clicks on the button we can instruct our application to do something.

The code for the MainActivity.java file is shown below. Copy and paste it to your project.

public class MainActivity extends ActionBarActivity {

    private EditText nameInput;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       nameInput = (EditText)findViewById(R.id.name_input);
       Button submitName = (Button)findViewById(R.id.submit_button);
       submitName.setOnClickListener(new OnClickListener(){
           @Override
           public void onClick(View view) {
              // get user input
              String enteredUserInput = nameInput.getText().toString();
              if(enteredUserInput.equals("") || enteredUserInput.length() < 6){
                 Toast.makeText(getApplicationContext(), "Invalid Usernam!! Please try again", Toast.LENGTH_LONG).show();
                 return;
           }
           Intent intent = new Intent(MainActivity.this, ReceiveTextActivity.class);
           intent.putExtra("SEND_TEXT", enteredUserInput);
           startActivity(intent);                                                
         }                                       
       });
      }

      @Override
      public boolean onCreateOptionsMenu(Menu menu) {
   // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
       return true;
      }
       @Override
       public boolean onOptionsItemSelected(MenuItem item) {
       // Handle action bar item clicks here. The action bar will
       // automatically handle clicks on the Home/Up button, so long
       // as you specify a parent activity in AndroidManifest.xml.
       int id = item.getItemId();
       if (id == R.id.action_settings) {
           return true;
       }
       return super.onOptionsItemSelected(item);
    }
}

The code above is getting the user input and validate if the EditText control is empty when the button is clicked or if the text entered is less than six characters. If any of the conditions hold true, an error message will be display to the user.

The android Intent class is used actions to be performed. You can read more about android Intent class here if you are not familiar with it.

To store the user input in the android bundle, the Intent class method called putExtra was used. The startActivity method of the Activity class starts new activity that has been passed as second parameter when the Intent class was instantiated.

Now we are going to create a new Activity file called ReceiveTextActivity. If you have done that, navigate to the activity_receive_text.xml file and add a TextView control. You can also copy and paste the code on the xml file. This code will create the TextView control for you.

<RelativeLayout 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"
    tools:context="com.example.test.ReceiveTextActivity" >

     <TextView
        android:id="@+id/receive_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="77dp"
        android:text="@string/hello_world" />

</RelativeLayout>

Let’s move to the ReceiveTextActivity file, we are going to retrieve the data / information passed from our MainActivity java file and assign it to the TextView control we have just created. Copy the code below and paste it in your ReceiveTextActivity.java file.

public class ReceiveTextActivity extends ActionBarActivity {

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

     TextView textContent = (TextView)findViewById(R.id.receive_text);
     // get the content of the data passed on the bundle
     Intent intent = getIntent();
     Bundle myIntentBundle = intent.getExtras();
     String saveContent = myIntentBundle.getString("SEND_TEXT");
     //set the text to the TextView Control
     textContent.setText(saveContent);
   }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
     // Inflate the menu; this adds items to the action bar if it is present.
     getMenuInflater().inflate(R.menu.receive_text, menu);
     return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
  // Handle action bar item clicks here. The action bar will
  // automatically handle clicks on the Home/Up button, so long
  // as you specify a parent activity in AndroidManifest.xml.

  int id = item.getItemId();
  if (id == R.id.action_settings) {
     return true;
  }
  return super.onOptionsItemSelected(item);
 }
}

This is the time to test if everything is working well. You can use your emulator to test it but I am using a real device.

If you want the complete source code for this simple project, you can get it by click the button below.

You can also drop your email and I will send the source code to you

I do hope everything works out for you but if you have any question or suggestion kindly use our comment box below.

One Response

Add a Comment