0

I've set up a fragment inside my activity, but I'm wondering how I can pass data from the activity into the fragment?

For example, this is my code:

    public class MyFragment extends Fragment 
{   
    private MyData _myData;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    {   
        // Inflate the layout for this fragment 
        return inflater.inflate(R.layout.custom_fragment, container, false);

        MyActivity activity = (MyActivity) getActivity(); // Unreachable code error here
        _myData = activity.getMyData();
    }
}

I need to be able to access the contents of the MyData object in the fragment. But when I try this code above, I get an "Unreachable Code" error, even though getMyData() is a public method in the MyActivity class.

b85411
  • 8,670
  • 14
  • 61
  • 114

2 Answers2

5

This line is the problem

return inflater.inflate(R.layout.custom_fragment_make_assembly_machine_location, container, false);

The return statement makes the function... return!, so following code never gets executed!

BenMorel
  • 31,815
  • 47
  • 169
  • 296
Merlevede
  • 8,078
  • 1
  • 23
  • 39
2

You have a return statement before

MyActivity activity = (MyActivity) getActivity();

Move the return statement to the last

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    {   
        MyActivity activity = (MyActivity) getActivity(); 
        _myData = activity.getMyData();
        return inflater.inflate(R.layout.custom_fragment, container, false);
    }

Also you may want to check

Send data from activity to fragment in android

Community
  • 1
  • 1
Raghunandan
  • 131,557
  • 25
  • 223
  • 252