Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start an Activity with a parameter

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.

like image 294
VansFannel Avatar asked Oct 12 '10 10:10

VansFannel


People also ask

How do I start my activity results?

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. In the above code, we have taken text view to show on Activity result data.


2 Answers

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"); 
like image 176
Wroclai Avatar answered Oct 02 '22 13:10

Wroclai


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"); 
like image 37
DavGin Avatar answered Oct 02 '22 13:10

DavGin