John smith
John smith

Reputation: 353

Android send interface through Intent

I have an activity (ActivityA) that implements an interface (InterfaceA). When I want to display an other activity I use this code :

Intent intent = new Intent(this, ActivityB.class);
// intent.putExtra("interface", this);
startActivity(intent);

And ActivityA

public class ActivityA extends Activity implements InterfaceA, Serializable

And then in ActivityB

Intent intent = getIntent();
Serializable s = intent.getExtras().getSerializable("interface");
if(s != null && s instanceof InterfaceA)
   iInterface = (InterfaceA)s;

But I get an error during

android java.io.NotSerializableException

Is it possible to send an Activity through an Intent (like delegate in Objective-C ?

Thanks

Upvotes: 4

Views: 1799

Answers (1)

Faraz
Faraz

Reputation: 2154

In ActivityB, I'm creating a new local object I want to display in ActivityA without having to refresh the listView in ActivityA.

You can start ActivityB for result in ActivityA as this will not recreate the ActivityA. And when you receive the result from ActivityB, add new object in list and call adapter's notifyDataSetChanged().

In ActivityA,

public static final int REQ_CODE = 1;

// Starting an activity
Intent intent = new Intent(this, ActivityB.class);
startActivityForResult(intent, REQ_CODE );

And override this method to get the result

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQ_CODE)
        {
            if(resultCode == Activity.RESULT_OK)
            {
                // Add the object in list and call adapter's notifyDataSetChanged()
            }
        }
    }

In ActivityB,

Intent data = new Intent();
// Put the new object as Serializable in Intent
setResult(Activity.RESULT_OK, data);
// And finally, close the activity
finish();

Upvotes: 3

Related Questions