Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android passing ArrayList<Model> to Fragment from Activity

Hi I want to send the data ArrayList<Division> to Fragment class ListContentFragment.

In MainActivity I am making a network call to get the data(JSON) and then parsing it to create ArrayList<Division>, now i want to populate the list view with the data i received (now in ArrayList<Division>)

MainActivity

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Adding Toolbar to Main screen
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Setting ViewPager for each Tabs
        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);
        // Set Tabs inside Toolbar
        TabLayout tabs = (TabLayout) findViewById(R.id.tabs);
        tabs.setupWithViewPager(viewPager);
        // Create Navigation drawer and inlfate layout
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
        // Adding menu icon to Toolbar
        ActionBar supportActionBar = getSupportActionBar();
        if (supportActionBar != null) {
            VectorDrawableCompat indicator
                    = VectorDrawableCompat.create(getResources(), R.drawable.ic_menu, getTheme());
            indicator.setTint(ResourcesCompat.getColor(getResources(),R.color.white,getTheme()));
            supportActionBar.setHomeAsUpIndicator(indicator);
            supportActionBar.setDisplayHomeAsUpEnabled(true);
        }
        // Set behavior of Navigation drawer
        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    // This method will trigger on item Click of navigation menu
                    @Override
                    public boolean onNavigationItemSelected(MenuItem menuItem) {
                        // Set item in checked state
                        menuItem.setChecked(true);

                        // TODO: handle navigation
                        Toast.makeText(MainActivity.this, "Clicked: " + menuItem.getTitle(), Toast.LENGTH_SHORT).show();

                        // Closing drawer on item click
                        mDrawerLayout.closeDrawers();
                        return true;
                    }
                });
        // Adding Floating Action Button to bottom right of main view
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Snackbar.make(v, "Hello Snackbar!",
                        Snackbar.LENGTH_LONG).show();
            }
        });

        // Network request test with volley
        NetworkRequests networkRequest = new NetworkRequests(this);
        networkRequest.fetchDummyData();
        divisionList = networkRequest.getDivisions();
    }

    // Add Fragments to Tabs
    private void setupViewPager(ViewPager viewPager) {
        Adapter adapter = new Adapter(getSupportFragmentManager());
        adapter.addFragment(new ListContentFragment(), "List");
        adapter.addFragment(new TileContentFragment(), "Tile");
        adapter.addFragment(new CardContentFragment(), "Card");
        viewPager.setAdapter(adapter);
    }

Fragment (currently its hard coded, want to populate with the ArrayList)

public class ListContentFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        RecyclerView recyclerView = (RecyclerView) inflater.inflate(
                R.layout.recycler_view, container, false);
        ContentAdapter adapter = new ContentAdapter(recyclerView.getContext());
        recyclerView.setAdapter(adapter);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        return recyclerView;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public ImageView avator;
        public TextView name;
        public TextView description;
        public ViewHolder(LayoutInflater inflater, ViewGroup parent) {
            super(inflater.inflate(R.layout.item_list, parent, false));
            avator = (ImageView) itemView.findViewById(R.id.list_avatar);
            name = (TextView) itemView.findViewById(R.id.list_title);
            description = (TextView) itemView.findViewById(R.id.list_desc);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Context context = v.getContext();
                    Intent intent = new Intent(context, DetailActivity.class);
                    intent.putExtra(DetailActivity.EXTRA_POSITION, getAdapterPosition());
                    context.startActivity(intent);
                }
            });
        }
    }

    /**
     * Adapter to display recycler view.
     */
    public static class ContentAdapter extends RecyclerView.Adapter<ViewHolder> {
        // Set numbers of List in RecyclerView.
        private static final int LENGTH = 18;

        private final String[] mPlaces;
        private final String[] mPlaceDesc;
        private final Drawable[] mPlaceAvators;

        public ContentAdapter(Context context) {
            Resources resources = context.getResources();
            mPlaces = resources.getStringArray(R.array.places);
            mPlaceDesc = resources.getStringArray(R.array.place_desc);
            TypedArray a = resources.obtainTypedArray(R.array.place_avator);
            mPlaceAvators = new Drawable[a.length()];
            for (int i = 0; i < mPlaceAvators.length; i++) {
                mPlaceAvators[i] = a.getDrawable(i);
            }
            a.recycle();
        }
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new ViewHolder(LayoutInflater.from(parent.getContext()), parent);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            holder.avator.setImageDrawable(mPlaceAvators[position % mPlaceAvators.length]);
            holder.name.setText(mPlaces[position % mPlaces.length]);
            holder.description.setText(mPlaceDesc[position % mPlaceDesc.length]);
        }

        @Override
        public int getItemCount() {
            return LENGTH;
        }
    }

}
like image 728
user986508 Avatar asked Oct 05 '16 07:10

user986508


People also ask

How can we send ArrayList from activity to fragment?

Intent intent = new Intent(getActivity(), StudentResult. class); intent. putExtra("ExtraData", allStudents); startActivity(intent); and in target class to show the objects in ListView();

How do you pass an ArrayList from activity to fragment in Kotlin?

If you want to pass an ArrayList to your fragment, then you need to make sure the Model class is implements Parcelable. Here i can show an example. then you can add ArrayList<ObjectName> to a Bundle object. ArrayList<ObjectName> arraylist = new Arraylist<ObjectName>(); Bundle bundle = new Bundle(); bundle.

How do I move a list from one fragment to another in Android?

To pass data from one fragment to another in android we simply make use of Bundle . In this example I am sending three String from MainActivityFragment(Fragment) to SecondFragment(Fragment) with the help of Bundle. Below is the code for the MainActivityFragment. Add the below code to your SecondFragment.


2 Answers

If you want to pass an ArrayList to your fragment, then you need to make sure the Model class is implements Parcelable. Here i can show an example.

public class ObjectName implements Parcelable {


    public ObjectName(Parcel in) {
        super();
        readFromParcel(in);
    }

    public static final Parcelable.Creator<ObjectName> CREATOR = new Parcelable.Creator<ObjectName>() {
        public ObjectName createFromParcel(Parcel in) {
            return new ObjectName(in);
        }

        public ObjectName[] newArray(int size) {

            return new ObjectName[size];
        }

    };

    public void readFromParcel(Parcel in) {
        Value1 = in.readInt();
        Value2 = in.readInt();
        Value3 = in.readInt();

    }

    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(Value1);
        dest.writeInt(Value2);
        dest.writeInt(Value3);
    }
}

then you can add ArrayList<ObjectName> to a Bundle object.

ArrayList<ObjectName> arraylist = new Arraylist<ObjectName>();  
Bundle bundle = new Bundle();  
bundle.putParcelableArrayList("arraylist", arraylist);
fragment.setArguments(bundle);

After this you can get back this data by using,

Bundle extras = getIntent().getExtras();  
ArrayList<ObjectName> arraylist  = extras.getParcelableArrayList("arraylist");

At last you can show list with these data in fragment. Hope this will help to get your expected answer.

like image 192
Alex Chengalan Avatar answered Oct 14 '22 18:10

Alex Chengalan


I was also stuck with the same problem . You can try this. Intead of sending the arraylist as bundle to fragment.Make the arraylist to be passed,as public and static in the activity.

public static Arraylist<Division> arraylist;

Then after parsing and adding the data in the arraylist make the call to the fragment.In the fragment you can the use the arraylist as:

ArrayList<Division> list=MainActivity.arraylist;
like image 26
Mayank Raj Avatar answered Oct 14 '22 18:10

Mayank Raj