Search code examples
javaandroidandroid-fragmentsarraylistfragmenttransaction

How to Pass ArrayList from Activity to Fragment in Android


I have a MainActivity and a fragment. What I want to do is pass array list from my main activity to my fragment.

In my MainActivity my code looks like this:

private final List<RestaurantParcelableModel> restaurantList = new ArrayList<>();
...
RestaurantsFragment restaurantsFragment = new RestaurantsFragment();
        Bundle args = new Bundle();
        args.putParcelableArrayList("restaurantList", (ArrayList<? extends Parcelable>) restaurantList);
        restaurantsFragment.setArguments(args);

        FragmentManager fragmentManager = getFragmentManager();
        android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.restaurants_list, restaurantsFragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();

Right now I am getting this error in fragmentTransaction.replace(R.id.restaurants_list, restaurantsFragment); - "Wrong 2nd argument type. Found: 'com.test.restaurants.sliderfragments.RestaurantsFragment', required: 'android.app.Fragment' replace (int, android.app.Fragment) in FragmentTransaction cannot be applied to (int, com.test.restaurants.sliderfragments.RestaurantsFragment)"


Solution

  • Now to fix the issue you have to handle your imports.

    Either use import android.app.Fragment instead of import android.support.v4.app.Fragment

    Or Update the main content of your app with a support Fragment manager like this:

    FragmentManager fragmentManager = getSupportFragmentManager(). 
    

    But then you also have to change the type of the FragmentManager itself; import android.app.FragmentManager to import android.support.v4.app.FragmentManager;