I want to pass an interface from 1st activity to 2nd activity.
I want to initiate methods from the interface from the 2nd activity which will affect the 1st activity.
I'm well aware that it's very overkilling not using the onActivityResult mechanism, and that it might not be good programming, but roll with me please.
Here's the issue - my interface can't implement Serializable / Parcelable since interface can't implement another class.
This is my interface :
public interface ITest {
void onSuccess(String text);
}
But, i can't start my activity with this interface since it's not Parcelable.
intent.putExtra("testInterface", new ITest() {
@Override
void onSuccess(String text) {
}
}
Obviously, i receive a compilation error :
Cannot resolve method 'putExtra(java.lang.String, ITest)'
You cannot "pass an interface". An "interface" is an abstract thing. What you want to pass is a concrete implementation of that interface, ie: an object (that happens to implement your interface). When you instantiate your "interface" (in your example, like this:
intent.putExtra("testInterface", new ITest() {
@Override
void onSuccess(String text) {
}
}
you are actually creating an instance of an anonymous class that implements the interface ITest
. To pass this in an Intent
you would need to make this class also implement Parcelable
or Serializable
.
However, even if you did that, it would not solve your problem. What you need to understand is that you can't pass objects (instances) by putting them as "extras" in an Intent
. When you do that, Android actually serializes and then deserializes the object so that you end up with 2 objects, one is a serialized/deserialized copy of the original.
If you want ActivityB
to communicate with ActivityA
, you will need to use another technique. Try one of these:
ActivityB
sends a broadcast Intent
, which ActivityA
listens forActivityA
starts ActivityB
using startActivityForResult()
and ActivityB
sends data back to ActivityA
using setResult()
public static
(ie: global) variables to communicateWhat you really need to understand is that, under certain conditions, the following can occur:
ActivityA
in the stack and ActivityB
on the top of the stackActivityB
, then calls onCreate()
, onStart()
and onResume()
of ActivityB
.In this case, there is no instance of ActivityA
anymore. That instance is dead. So ActivityB
cannot communicate with ActivityA
because it no longer exists.