Start an Activity with a parameter
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");
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");
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");
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)