Let's suppose 2 activities Activity1
and Activity2
. I need to call method methodAct1()
(inside Activity1
) from methodAct2
(inside Activity2
). I think it should work using callback listener - I don't want to use EventBus
libs!
I get java.lang.NullPointerException
using this code:
interface:
public interface MyListener {
public void listen();
}
Activity where event is created:
public class Activity2 extends Activity {
private MyListener myListener;
public void setUpListener(MyListener myListener) {
this.myListener = myListener;
}
private void doWork(){
//do stuff
myListener.listen();
}
}
Activity where I'd like to get that event when work is done:
public class Activity1 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Activity2 activity2 = new Activity2();
activity2.setUpListener(new setUpListener() {
@Override
public void listen() {
// get the event here
}
});
}
}
This is absolutely not possible. You never instanciate a new Activity yourself. You will not have two Activities running at the same time.
If you want another Activity to do something, based on what your previous Activity wants, then you need to add that to your Intent.
Intent intent = new Intent(this, Activity2.class);
intent.putExtra("data field", "data value");
startActivity(intent);
If you want specific functionality through a callback then you might be thinking of Fragments. In this way, you can have the same Activity running and it can tell individual Fragments what they need to do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With