Skip to content Skip to sidebar Skip to footer

Passing Object From Fragment To Activity

Question: How do I pass objects from fragment to activity (on request from activity). Background: I am using Android Studio and have set up a new tabbed activity from the New Andro

Solution 1:

You could have an interface:

publicinterfaceMyInterface {
    voiddoSomethingWithData(Object data);
}

then in the activity class:

publicclassMyActivityextendsActivityimplementsMyInterface {
    ...
    publicvoiddoSomethingWithData(Object data) {
        // save your data in database
    }
    ...
}

and in fragments:

publicclassMyFragmentextendsFragment {
    ...
    privateMyInterface listener;
    ...
    @OverridepublicvoidonAttach(Context context) {
        super.onAttach(context);
        if (context instanceofMyInterface) {
            listener = (MyInterface) context;
        }
    }

    @OverridepublicvoidonDetach() {
        listener = null;
        super.onDetach();
    }
    ...
    // Somewhere in code .. where you want to send data to the activity
    listener.doSomethingWithData(data);
    ...
}

Solution 2:

The Activity has instances of the fragments, so when you are pressing the Add button, you can collect your data from the fragments.

for example, from the TabActivity:

intcards= fragment1.getCards();
Stringname= fragment2.getUserName();

etc.

Just create does public methods in the Fragments.

Solution 3:

You can create one DataManger Singelton classs and in that decalare getter setter of the object and use it throughout your project.

Post a Comment for "Passing Object From Fragment To Activity"