TrinityTuts Tips

Pass data from activity to fragment in android

In some cases we need to pass data from Activity to its fragment, we also do that by creating constructor but that create some issue when you make final release you need to create final constructor or empty constructor etc. So the best way to that by using bundle in bundle you pass your data by setting data in it and get that inside your fragment onCreateView().

Sample

Bundle bundle = new Bundle();
bundle.putString("data", "Data you want to send");
// Your fragment
MyFragment obj = new MyFragment();
obj.setArguments(bundle);

Get data in your fragment.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    String data = getArguments().getString("data");    
    return inflater.inflate(R.layout.myfragment, container, false);
}

😉