HOW PASS DATA FROM ACTIVITY TO FRAGMENT AND VICE-VERSA

Here we will learn that how to pass the data from activity to fragment and fragment to activity step by step:

Passing data from Activity to Fragment

According to the below code we are sending string “suman kumar” with the parameter “name”.Here with help of “name” parameter we can get the string “suman kumar” in the Fragment.

Activity

Bundle bundle=new Bundle();
bundle.putString("name","suman kumar");
//setting the argument which we want to pass to the fragment
FragmentClass obj=new FragmentClass(); 
obj.setArguments(bundle);

Now,Here we will get the “suman kumar” in Fragment class from the Activity class.

Fragment

 @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Bundle bundle = this.getArguments();
        String nameinfragment= bundle.getString("name");
        
        }

Passing data from Fragment to Activity

According to the below code we are sending string “suman kumar” with the parameter “name”.Here with help of “name” parameter we can get the string “suman kumar” in the Activity.

Fragment

Intent intent=new Intent(getActivity,SecondActivity.class);
intent.putExtra("name",suman kumar");
startActivity(intent);

Now,Here we will get the “suman kumar” in the activity from Fragment.

Activity

SecondActivity obj=(SecondActivity)getActivity();
String nameinactivity=obj.getIntent.getExtras().getString("name");

Conclusion :

I hope that the above tutorial will help you for your project development and interview purpose for the both fresher and experience candidate.

sumankumar80

Hello Friends,I have written and developed this website because you can learn technology easily ,prepare for the placement and also for the any type of examination . By :Suman Kumar

Leave a Reply

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