Pass data from fragment to activity

This is my preferred solution from the stackoverflow answers seen (mainly this one from Harlo Holmes).

Any fragment that should pass data back to its containing activity should declare an interface to handle and pass the data. Then make sure your containing activity implements those interfaces. For example:

In your fragment, declare the interface.

public interface OnDataPass {
    public void onDataPass(String data);

Then, connect the containing class’ implementation of the interface to the fragment in the onAttach method, like so:

OnDataPass dataPasser;

public void onAttach(Activity a) {
    dataPasser = (OnDataPass) a;

Within your fragment, when you need to handle the passing of data, just call it on the dataPasser object:

public void passData(String data) {

Finally, in your containing activity which implements OnDataPass.

public void onDataPass(String data) {
    Log.d("LOG","hello " + data);

Apparently should provide 2 way communication and should allow fragments to communicate with each other.

This entry was posted in Android. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *