Seriescw Esxille
Seriescw Esxille

Reputation: 301

How to pass Parcelable object from child to parent activity?

I'm building a small app that requiere authentication. In my main activity I have a Parcelable class named "user" that contains the username and password of an user, when a user click on a button it starts a new activity passing that user class. It works like a charm, in the child activity the user fill the form to authenticate, then when user press the back button, I would like to send the "user" class back to my main activity.

Is it possible to do that ??

Upvotes: 3

Views: 5136

Answers (1)

rciovati
rciovati

Reputation: 28063

Start your child activity with:

startActivityForResult(startIntent, 1);

In your child activity, intercept the back button and append your data:

@Override
public void onBackPressed() {
    Intent data = new Intent();
    data.putExtra("key", yourDataHere);
    setResult(Activity.RESULT_OK, data);
    super.onBackPressed();
}

And get data inside parent activity inside onActivityResult

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == 1 && resultCode == Activity.RESULT_OK){
        DataType yourData = (DataType) data.getParcelableExtra("key");
        //Do whatever you want with yourData
    }
}

Upvotes: 13

Related Questions