Umair Abdulsattar
Umair Abdulsattar

Reputation: 11

How to use a bundle for sending data to fragment from an activity in Android Studio

I am trying to build simple movies name list in recyclerview inside drawer layout when I click any movie name show me the detail of movie like an image, textView in another fragment. How to implement a bundle for sending data to fragment from an activity.This is my main activity

Upvotes: 0

Views: 108

Answers (2)

Abhishek Sharma
Abhishek Sharma

Reputation: 281

You can send data from your activity to fragment like this:

In your MainActivity , add fragment when you want to open detail fragment

 addFragment(R.id.frame_container,MovieDetailFragment.getInstance(/*your data*/),tag_name);
 //then commit

In your Movie Detail Fragment,

 public static MovieDetailFragment(//your data//){
   MovieDetailFragment detailFragment  new MovieDetailFragment();
   Bundle bundle = new Bundle();
   bundle.putString(key,//yourdata//);//you can use any type you want to put in bundle
   detailFragment.setArguments(bundle);
   return movieDetailFragment;
 }

and in your MovieDetailFragment's onCreateView() , you can get your data from bundle like this:-

  if(getArguments()!=null){
    String data = getArguments().getString(key);
  }

I hope it will solve your query!!

Upvotes: 1

No Body
No Body

Reputation: 681

Step 1: Passing the data from activity to fragment,

Bundle bundle = new Bundle();
bundle.putString("params", "My String data");
set MyFragment Arguments
MyFragment myObj = new MyFragment();
myObj.setArguments(bundle);

Step 2: Receiving the data to the fragment,

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString("params");
        }
    }

Upvotes: 0

Related Questions