Start an Activity with a parameter
Asked Answered
R

5

323

I'm very new on Android development.

I want to create and start an activity to show information about a game. I show that information I need a gameId.

How can I pass this game ID to the activity? The game ID is absolutely necessary so I don't want to create or start the activity if it doesn't have the ID.

It's like the activity has got only one constructor with one parameter.

How can I do that?

Thanks.

Roer answered 12/10, 2010 at 10:19 Comment(0)
L
551

Put an int which is your id into the new Intent.

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
Bundle b = new Bundle();
b.putInt("key", 1); //Your id
intent.putExtras(b); //Put your id to your next Intent
startActivity(intent);
finish();

Then grab the id in your new Activity:

Bundle b = getIntent().getExtras();
int value = -1; // or other values
if(b != null)
    value = b.getInt("key");
Legitimist answered 12/10, 2010 at 10:35 Comment(7)
You may want to make sure b != null before you start grabbing from itSpecialty
How can "b" be null in second activity in this code? I get b is null on create method of second activity.Ylangylang
B can be null, lets say you want to start this activity from another place and you do it the standard way, with no params. It will throw a NPE. You should always consider this params optional.Amethyst
It is not necessary to create a new Bundle (and if you do the documentation says you "must" use the package name to prefix your keys.) Simply use intent.putExtra(String, Int).Fugleman
One could argue that its better not to do a null check. en.wikipedia.org/wiki/Fail-fast.Delitescence
@Delitescence One could argue that, but if the argument is optional then passing null is not an error.Serena
@AndreasMagnusson I didn't realize the OP explicitly stated the argument is optional. Good call.Delitescence
S
137

Just add extra data to the Intent you use to call your activity.

In the caller activity :

Intent i = new Intent(this, TheNextActivity.class);
i.putExtra("id", id);
startActivity(i);

Inside the onCreate() of the activity you call :

Bundle b = getIntent().getExtras();
int id = b.getInt("id");
Skillet answered 12/10, 2010 at 10:37 Comment(5)
is it okay to pass in a custom object type ?Leavelle
@Leavelle No, you have to use a bundle like in the accepted answer.Estate
See this @Leavelle : #14333949Meow
This answer should have been the accepted one. The whole Bundle nonsense is unnecessary.Acyclic
@Leavelle looking at the signature of the API it looks like any custom types need to be parcelable or serialisable. Presumablly because the andriod activity API is designed on the assumptoin that the new activity may be in a differnet process.Bottomless
T
42

I like to do it with a static method in the second activity:

private static final String EXTRA_GAME_ID = "your.package.gameId";

public static void start(Context context, String gameId) {
    Intent intent = new Intent(context, SecondActivity.class);
    intent.putExtra(EXTRA_GAME_ID, gameId);
    context.startActivity(intent);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    ... 
    Intent intent = this.getIntent();
    String gameId = intent.getStringExtra(EXTRA_GAME_ID);
}

Then from your first activity (and for anywhere else), you just do:

SecondActivity.start(this, "the.game.id");
Thamora answered 5/3, 2015 at 16:16 Comment(4)
Exactly what I was looking for! Thank youPernas
In the onCreate method shouldn't String gameId = intent.getStringExtra(EXTRA_EXTERNAL_ID); be String gameId = intent.getStringExtra(EXTRA_GAME_ID);Villanelle
Having statics will make Your testing very hard.Insensibility
Is this a memory leak? Passing the context into a static method seems like a bad idea to me. Why not just return the intent and then start the activity using that intent from the first class?Furness
H
7

Kotlin code:

Start the SecondActivity:

startActivity(Intent(context, SecondActivity::class.java)
    .putExtra(SecondActivity.PARAM_GAME_ID, gameId))

Get the Id in SecondActivity:

class CaptureActivity : AppCompatActivity() {

    companion object {
        const val PARAM_GAME_ID = "PARAM_GAME_ID"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val gameId = intent.getStringExtra(PARAM_GAME_ID)
        // TODO use gameId
    }
}

where gameId is String? (can be null)

Heilner answered 13/8, 2018 at 11:4 Comment(0)
A
3

The existing answers (pass the data in the Intent passed to startActivity()) show the normal way to solve this problem. There is another solution that can be used in the odd case where you're creating an Activity that will be started by another app (for example, one of the edit activities in a Tasker plugin) and therefore do not control the Intent which launches the Activity.

You can create a base-class Activity that has a constructor with a parameter, then a derived class that has a default constructor which calls the base-class constructor with a value, as so:

class BaseActivity extends Activity
{
    public BaseActivity(String param)
    {
        // Do something with param
    }
}

class DerivedActivity extends BaseActivity
{
    public DerivedActivity()
    {
        super("parameter");
    }
}

If you need to generate the parameter to pass to the base-class constructor, simply replace the hard-coded value with a function call that returns the correct value to pass.

Accomplished answered 27/8, 2014 at 1:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.