简体   繁体   中英

Getting data from an Activity in a Fragment

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.

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM