Passing Data to Activities Using the Android SDK

Passing data between activities is an essential feature in most applications. There a number ways this can be done; adding data to intents, storing local data in flat files, storing and querying data in a local database. In this tutorial we’ll be adding data to intents in order to pass data to another activity. This is probably one of the easiest and most volatile ways of moving data between activities.

If you haven’t created an Android project yet, check out my posts Creating Your First Android Project – Creating An Activity and Creating Another Activity – Intro to Android Intents. This tutorial will assume you’re familiar with the components discussed in the posts I just mentioned.

Finally Let’s Start Passing Data

Start by creating a new project. I’ll be naming the project IntentData. The first empty activity will be named ParentActivity and I’ll create a second activity named ChildActivity.

Next, similar to my intro to intents tutorial, we need to add a button and the onClick event’s functionality.

In the ParentActivity.java file add the following under the onCreate method:

public void onCLickChildActivity(View view){
    Intent intent = new Intent(this, ChildActivity.class);
    intent.putExtra(Intent.EXTRA_TEXT, "Some Data!");
    startActivity(intent);
}

Passing-Data-Child-Activity

Next add the button to the activity_parent.xml.

   <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/buttonOpenChild" android:text="@string/app_name" android:layout_centerVertical="true" android:layout_centerHorizontal="true" android:onClick="onCLickChildActivity"/>

Passing-Data-Child-Layout

In the activity_child.xml file we want to add a textView component.

    <TextView android:id="@+id/parentTextData" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="" />

Passing-Data-Child-Layout

Finally we’ll add some functionality to display the data we’ve sent to the child activity. Add the following lines to the bottom of the onCreate method of the ChildActivity.java file:

    TextView parentData = (TextView)findViewById(R.id.parentTextData);
    if(getIntent() != null && getIntent().hasExtra(Intent.EXTRA_TEXT)){
        parentData.setText(getIntent().getStringExtra(Intent.EXTRA_TEXT));
}

Passing-Data-Child-Activity

Done! Run the application and click the button. You’ll see the second activity opened will contain the text ‘Some Data!’ from the parent activity.

Passing data from one activity to the next is fairly easy. The code above uses intents to store key value pairs of information for passing and retrieving data.

Try some other data types! Arrays maybe? Structures even? Stay tuned for answers.

Leave a Reply

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