Skip to content Skip to sidebar Skip to footer

How To Pass Values From Fragment To Activity

I am new in Android Development. I am trying to pass values from fragment to activity, but after so many tries I am unable to get the answer... This is my Fragment : public OtpGent

Solution 1:

You should create an interface in your fragment and you should implement the interface to your Activity class.

For example, in your Fragment :

OnHeadlineSelectedListener mCallback;

    // Container Activity must implement this interfacepublicinterfaceOnHeadlineSelectedListener {
        publicvoidonArticleSelected(int position);
    }

    @OverridepublicvoidonAttach(Context context) {
        super.onAttach(context);

        // This makes sure that the container activity has implemented// the callback interface. If not, it throws an exceptiontry {
            mCallback = (OnHeadlineSelectedListener) activity;
        } catch (ClassCastException e) {
            thrownewClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }

you can send any value like this:

// Send the event to the host activity
        mCallback.onArticleSelected(position);

And your activity should be like this :

publicstaticclassMainActivityextendsActivityimplementsHeadlinesFragment.OnHeadlineSelectedListener{
    ...

    publicvoidonArticleSelected(int position) {
        // The user selected the headline of an article from the HeadlinesFragment// Do something here to display that article
    }
}

For more information you can check the offical documentation :

Solution 2:

This is the solution i use , This works but its not a good practice

Inside your activity write getters and setters for the data which you want to pass , for example if you want to pass a string name write

String   fileName;

 publicStringgetFileName() {
    return fileName;
}
publicvoidsetFileName(String fileName) {
    this.fileName = fileName;
}

in your fragment

publicclassYourFragmentextendsFragment {

    Context contextCheckClass;
    privateString fileName;



@OverridepublicViewonCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View group=(View)inflater.inflate(R.layout.fragment_highlight, null);

         fileName=((MainActivity) getActivity()).setFileName("Your String to pass to activity");    //set what ever string you want to passreturn group;
}

 }

if you do this way you cant use this fragment at any other location that MainActivity

if you want to access the same fragment from different activities then

in your fragment create a constructor passing context .You would notice that it will give a warning about avoiding non default constructors just ignore it or disable check

publicclassYourFragmentextendsFragment {

    private String fileName;
    Context contextCheckClass;

    publicYourFragment(Context ctx) {
        this.contextCheckClass=ctx;
    }

@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View group=(View)inflater.inflate(R.layout.fragment_highlight, null);
    if(contextCheckClass instanceof MainActivity){ //write your Activity name here//This fragment is called from MainActivity
         fileName=((MainActivity) getActivity()).getFileName(); 

        }
        else {
        //This fragment is called from some other activity
         }

    return group;
}

To Load this Fragment pass activity context to it

 YourFragment yourFragment =new YourFragment (MainActivity.this);
 getSupportFragmentManager()
.beginTransaction()
.add(R.id.LL_Fragment, yourFragment)
.addToBackStack(null)
.commit();

Solution 3:

For someone who might come here sometime, please be informed that the answers in this thread have become outdated. The Fragment library now provides two options for communication: a shared ViewModel and the Fragment Result API. Please refer to the official docs here.

Post a Comment for "How To Pass Values From Fragment To Activity"