Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Pushing String Values Using Intent.putExtra()

Author: Ulysses Levy
Published? true
FormatLanguage: WikiFormat

Problem:

You need to pass some parameters into an activity while launching it.

Solution:

A quick solution is to use Intent.putExtra() to push our data. And then use getIntent().getExtras().getString() to retrieve it.

Discussion:

Contents


Push Data


import android.content.Intent;

    ...

    Intent intent = 
        new Intent( 
            this, 
            MyActivity.class );
    intent.putExtra( "paramName", "paramValue" );
    startActivity( intent );

The above code might be inside the main activity. "MyActivity.class" is the second Activity we want to launch; it must be explicitly included in your AndroidManifest.xml file.


    <activity android:name=".MyActivity" />

Pull Data


import android.os.Bundle;

    ...

    Bundle extras = getIntent().getExtras();
    if (extras != null)
    {
        String myParam = extras.getString("paramName");
    }
    else
    {
        //..oops!
    }

In this example, the above code would be inside your MyActivity.java file.

Gotchas

This method can only pass strings. So let's say you need to pass an ArrayList to your ListActivity; a possible workaround is to pass a comma-separated-string and then split it on the other side.

Alternative Solutions

Use SharedPreferences

See Also:

[1], [2].

No records found.