Java – Send data (ArrayList) from an activity to a fragment

Send data (ArrayList) from an activity to a fragment… here is a solution to the problem.

Send data (ArrayList) from an activity to a fragment

I only have one activity and only one related fragment. Fragment is part of Navigation Lader. Now I have an ArrayList<String> constantly changing. I want to do so that whenever I open the Navigation Lader, the ArrayList should be passed to the Fragment

Fragment has a ListView populated with an ArrayList

This is the Activity code for Toolbar and DrawerLayout:

toolbar = (Toolbar) findViewById(;

OnlineNavDrawerFragment drawerFragment = (OnlineNavDrawerFragment)
drawerFragment.setUp((DrawerLayout) findViewById(, toolbar);

This is the corresponding code for Fragment:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
     Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_online_nav_drawer, container, false);
    ListView lvOnline = (ListView) view.findViewById(;
    return view;

public void setUp(DrawerLayout drawerLayout, Toolbar toolbar) {
    mDrawerLayout = drawerLayout;
    mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout,
            toolbar, R.string.drawer_open, R.string.drawer_close) {

        public void onDrawerOpened(View drawerView) {

        public void onDrawerClosed(View drawerView) {
    mDrawerLayout.setDrawerListener(mDrawerToggle); Runnable() {
        public void run() {

I’m faced with the following problem: how to < String > via ArrayList from Activity to Fragment

Also, I don’t see what bit of code in the activity I can actually pass the data.

PS: Most of the code is a modified version of the code shown in the YouTube video series. It operates in its current form.


Do this in your fragment.

GetDataInterface sGetDataInterface;

public interface GetDataInterface {
    ArrayList<String> getDataList();

public void onAttach(Activity activity) {
    try {
        sGetDataInterface= (GetDataInterface) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString() + "must implement GetDataInterface Interface");

public void onResume() {
    if(sGetDataInterface != null){
            mData = sGetDataInterface.getDataList();

In your main activity

public class MainActivity implements YourFragmentName.GetDataInterface {
    public ArrayList<String> getDataList() {
        return mDataArrayList;

Related Problems and Solutions