Java – Activity to Activity callback listener

Activity to Activity callback listener… here is a solution to the problem.

Activity to Activity callback listener

Consider that there are 2 Activity Activity1 and Activity 2. I need to call methodAct1() from methodAct2 (inside Activity2). I think it should work with callback listeners – I don’t want to use the EventBus library!

I used this code to get java.lang.NullPointerException:

Interface:

public interface MyListener {
    public void listen();
}

Create the event’s activity:

public class Activity2 extends Activity {

private MyListener  myListener;

public void setUpListener(MyListener myListener) {
        this.myListener = myListener;
    }

private void doWork(){
        do stuff 
        myListener.listen();
    }
}

I expect to get the Activity :for that event when the work is complete

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

}
        });
    }
}

Solution

This is absolutely impossible. You would never instantiate a new activity yourself. You do not run two activities at the same time.

If you want another activity to perform something based on the requirements of your previous activity, then you need to add it to your intent.

Intent intent = new Intent(this, Activity2.class);
intent.putExtra("data field", "data value");
startActivity(intent);

If you want to implement a specific function with callbacks, then you might think of Fragments Activity, which tells individual fragments what they need to do.

Related Problems and Solutions