Skip to content Skip to sidebar Skip to footer

Activity To Activity Callback Listener

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

Solution 1:

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 = newIntent(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.

Solution 2:

The NPE is happening because of your statement:

Activity2activity2=newActivity2(); <--

you should never do this, and instead you should do in the Activity 1:

Intent intent = newIntent(this, Activity2.class);
intent.putExtra("dataKey", "dataValue");
startActivityForResult(pickContactIntent, CALLBACK_REQUEST);

the startActivityForResult() offers a callback from Activity 2 to Activity 1, and you have to override the result in activity 1:

@OverrideprotectedvoidonActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding toif (requestCode == CALLBACK_REQUEST) {
        // Make sure the request was successfulif (resultCode == RESULT_OK) {
            // The Intent's data Uri identifies which contact was selected.// Do something with the contact here (bigger example below)
        }
    }
}

Solution 3:

You could do that in your approach like this....

publicclassActivity2extendsAppCompatActivity {

    privatestaticMyListener  myListener;

    publicstaticvoidsetUpListener(MyListener Listener) {
        myListener = Listener;
    }

    publicvoiddoWork(View view) {
        myListener.listen();
    }
}


publicclassActivity1extendsAppCompatActivity {

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Activity2.setUpListener(newMyListener() {
            @Overridepublicvoidlisten() {
                Log.d("Hello", "Hello World");
            }
        });
    }

    publicvoidgoToAnotherActivity(View view) {
        startActivity(newIntent(Activity1.this, Activity2.class));
    }
}

Though it's not best approach and in order to work with this mechanism your activity1 needs to be created.

Solution 4:

You can do it like this > - STEP 01: Implement a shared interface


publicinterfaceSharedCallback {
    public String getSharedText(/*you can define arguments here*/);
}
  • STEP 02: Implement a shared class

final classSharedMethode {
    privatestaticContext mContext;

    privatestaticSharedMethode sharedMethode = newSharedMethode();

    privateSharedMethode() {
        super();
    }

    publicstaticSharedMethodegetInstance() {
        return sharedMethode;
    }

    publicvoidsetContext(Context context) {
        if (mContext != null)
            return;

        mContext = context;
    }

    publicbooleancontextAssigned() {
        return mContext != null;
    }

    publicContextgetContext() {
        return mContext;
    }

    publicvoidfreeContext() {
        mContext = null;
    }
}

- STEP 03 :: Play with code in First Activity


publicclassFirstActivityextendsActivityimplementsSharedCallback {
    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_layout);

        // call playMe from here or thereplayMe();
    }

    privatevoidplayMe() {
        SharedMethode.getInstance().setContext(this);
        Intent intent = newIntent(this, SecondActivity.class);
        startActivity(intent);
    }

    @OverridepublicStringgetSharedText(/*passed arguments*/) {
        return"your result";
    }

}
  • STEP 04 :: Finalize the game in SecondActivity

publicclassSecondActivityextendsActivity {

    privateSharedCallback sharedCallback;

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_layout);

        if (SharedMethode.getInstance().contextAssigned()) {
            if (SharedMethode.getInstance().getContext() instanceofSharedCallback)
                sharedCallback = (SharedCallback) SharedMethode.getInstance().getContext();

            // to prevent memory leak. no further needsSharedMethode.freeContext();
        }

        // You can now call your implemented methodes from anywhere at any timeif (sharedCallback != null)
            Log.d("TAG", "Callback result = " + sharedCallback.getSharedText());

    }

        @OverrideprotectedvoidonDestroy() {
        sharedCallback = null;
        super.onDestroy();
    }

}

you can also implement a backword callback (from First to Second) to get some results from SecondAvtivity or call some methods

Post a Comment for "Activity To Activity Callback Listener"