Skip to content

fefong/android_callActivity

Repository files navigation

Android/Java Start another Activity

Example Application: Call Activity | Start Another Activity - Android

Start Activity

Simple start another activity

Structure for startActivity:

Intent i = new Intent(MainActivity.this, SecondActivity.class);

startActivity(i);

startActivity

Start Activity with Put Extra

Initialize another activity with parameters Using different types of parameters

Set PutExtras

Structure for startActivity with putExtras:

Intent i = new Intent(MainActivity.this, SecondActivity.class);

i.putExtra(getString("KEY", "StringValueExtra");

startActivity(i);

startActivityPutExtra

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);

Get PutExtras

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
     }
}

Start Activity for Result

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();

⚠️ Necessary Override method onActivityResult on first activity.

@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
            }
        }
    }  

}

startActivityForResult

Some links for more in depth learning