Example Application: Call Activity | Start Another Activity -
Simple start another activity
Structure for startActivity:
Intent i = new Intent(MainActivity.this, SecondActivity.class);
startActivity(i);
Initialize another activity with parameters Using different types of parameters
- String;
- Integer;
- Long;
- Boolean;
- Drawable;
- Model (Class Person)
Structure for startActivity with putExtras:
Intent i = new Intent(MainActivity.this, SecondActivity.class);
i.putExtra(getString("KEY", "StringValueExtra");
startActivity(i);
Example
Intent i = new Intent(MainActivity.this, SecondActivity.class);
i.putExtra(getString(R.string.EXTRA_STRING), "StringValueExtra");
i.putExtra(getString(R.string.EXTRA_INT), 1);
i.putExtra(getString(R.string.EXTRA_LONG), 1L);
i.putExtra(getString(R.string.EXTRA_BOOLEAN), true);
i.putExtra(getString(R.string.EXTRA_DRAWABLE), R.drawable.ic_android);
i.putExtra(getString(R.string.EXTRA_MODEL), new Person("NamePerson", "AnyPersonValue"));
startActivity(i);
-
How to create model? How to do the Getters and Setters?
-
How to declare variables?
-
See strings.xml
In the second activity:
Intent i = getIntent();
Bundle extras = i.getExtras();
Check has extras (PutExtras)
if (extras == null) {
//TODO
}
Check contains key PutExtra
if (extras.containsKey("KEY"){
//TODO
}
Example
if (extras != null) {
if (extras.containsKey("KEY"){
//TODO
}
}
Declare variable for request code.
int CODE_ANY = 100; // ANY VALUE;
Intent i = new Intent(MainActivity.this, SecondActivity.class);
startActivityForResult(i, CODE_ANY));
In the second activity
Intent i = new Intent();
i.putExtra("KEY", "THIS VALUE RETURN ACTIVITY FOR RESULT");
setResult(RESULT_OK);
finish();
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if( requestCode == CODE_ANY)) {
if (resultCode == RESULT_OK) {
if(data != null){
if(data.getExtras().containsKey("KEY")){
// TODO - has extra
}
}
}
}