I want a recyclerView that fetches data from Firebase real-time database. But the database nodes contain data with different model classes. Now how can I detect which model class I need to use depending on the dataSnapshot.
Asked
Active
Viewed 167 times
-4
-
Please check the duplicate to see how you can use two different classes. – Alex Mamo Feb 13 '19 at 15:51
2 Answers
1
You don't need multiple adapter you need multiple ViewHolders, check this How to create RecyclerView with multiple view type?
@Override
public int getItemViewType(int position) {
//... if item is instance of ModelA return 0
//... if item is instance of ModelB return 1
}
Then in onCreateViewHolder
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case 0: return new ViewHolder0(...);
case 1: return new ViewHolder1(...);
...
}
}
and in onBindViewHolder
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
switch (holder.getItemViewType()) {
case 0:
ViewHolder0 viewHolder0 = (ViewHolder0)holder;
...
break;
case 1:
ViewHolder1 viewHolder1 = (ViewHolder1)holder;
...
break;
}
}

svkaka
- 3,942
- 2
- 31
- 55
1
If by multi-adapter you mean to display more than one type of recyclerViewItem in the recyclerView, then just override getItemViewType method in your adapter class, and then in onCreateViewHolderHolder you can inflate the recyclerItemLayouts accordingly by checking viewType argument.
Check this out for more info: https://www.journaldev.com/12372/android-recyclerview-example

Kashish Sharma
- 749
- 8
- 18
-
All different types of data are in the same node with different push id. Now how can I detect which types of json data are coming(ie. for the first time say name:Bhaskar, age:22 and for the second download the data are say district:Jorhat, country: India etc) . – Bhaskar Jyoti Dutta Feb 13 '19 at 15:37
-
And also why negative marking is done in my question. Who is giving me this? If you do not like my question then you should not answer, but why give me negative marks. Although I don't care about the negative or positive marks yet it makes me angry. – Bhaskar Jyoti Dutta Feb 13 '19 at 15:48
-
You've to understand what sort of JSON data you're dealing with. eg. You can make a view for JSON objects having "name" as a key, and another for data having "district" as key. And to avoid downvotes on your question, try searching them in the existing or already answered questions, keep them to the point etc. Happy Coding !! – Kashish Sharma Feb 13 '19 at 16:30
-
I have added the comment below your answer because I did not find any other place to add that comment. But I was not pointing to you, I was pointing to the downvoters. Sorry for this. Your link is helpful. – Bhaskar Jyoti Dutta Feb 13 '19 at 18:01