populate data on appropriate Section in recyclerView (Java) - java

i have a recyclerView where i added some sections using this library
and my RecyclerView is now looking like this
as you can see that my data is not organised yet, right now my data is on this form :
Section 2015
2016-05-03
2016-04-03
2015-12-03
Section 2016
2016-05-03
2016-04-03
2015-12-03
i want it to be like :
Section 2015
2015-12-03
Section 2016
2016-05-03
2016-04-03
as you can see i want to manage the data according to their value and section's value
this is my MainAdapter Class:
public class MainAdapter extends SectionedRecyclerViewAdapter<MainAdapter.MainVH> {
Context context;
LayoutInflater inflater;
List<Data> dataArray = Collections.emptyList();
ArrayList<String> data;
ArrayList<String > sectionData;
public MainAdapter(Context context ,ArrayList<String> data , ArrayList<String> sectionData ){
inflater = LayoutInflater.from(context);
this.context = context;
this.data = data;
this.sectionData = sectionData;
}
#Override
public int getSectionCount() {
return sectionData.size(); // number of sections.
}
#Override
public int getItemCount(int section) {
return data.size(); // odd get 8
// return 8; // number of items in section (section index is parameter).
}
#Override
public void onBindHeaderViewHolder(MainVH holder, int section) {
// Setup header view.
String current = sectionData.get(section);
holder.title.setText(current);
}
#Override
public void onBindViewHolder(MainVH holder, int section, int relativePosition, int absolutePosition) {
// Setup non-header view.
// 'section' is section index.
// 'relativePosition' is index in this section.
// 'absolutePosition' is index out of all non-header items.
// See sample project for a visual of how these indices work.
if (data.get(relativePosition).contains("2015")){
Toast.makeText(context , "it contains 2015",Toast.LENGTH_SHORT).show();
}
String currentRow = data.get(relativePosition);
holder.title.setText(currentRow);
// holder.title.setText(String.format("S:%d, P:%d, A:%d", section, relativePosition, absolutePosition));
}
#Override
public int getItemViewType(int section, int relativePosition, int absolutePosition) {
if (section == 1)
return 0; // VIEW_TYPE_HEADER is -2, VIEW_TYPE_ITEM is -1. You can return 0 or greater.
return super.getItemViewType(section, relativePosition, absolutePosition);
}
#Override
public MainVH onCreateViewHolder(ViewGroup parent, int viewType) {
// Change inflated layout based on 'header'.
int layout;
switch (viewType) {
case VIEW_TYPE_HEADER:
layout = R.layout.section;
break;
case VIEW_TYPE_ITEM:
layout = R.layout.row;
break;
default:
Toast.makeText(context,"Default",Toast.LENGTH_SHORT).show();
break;
}
View v = LayoutInflater.from(parent.getContext())
.inflate(viewType == VIEW_TYPE_HEADER ? R.layout.section : R.layout.row, parent, false);
return new MainVH(v);
}
public static class MainVH extends RecyclerView.ViewHolder {
final TextView title;
public MainVH(View itemView) {
super(itemView);
// Setup view holder.
// You'd want some views to be optional, e.g. for header vs. normal.
title = (TextView) itemView.findViewById(R.id.TV);
}
}
}
and this is my MainActivity :
public class MainActivity extends AppCompatActivity {
MainAdapter mainAdapter;
RecyclerView recyclerView;
ArrayList<String> mData;
ArrayList<String > mDataSection,RawmDataSection;
ArrayList<Data> managedDataArray;
HashMap hMap;
ArrayList<ArrayList<String>> organizedData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mData = new ArrayList<String>();
mDataSection = new ArrayList<String>();
RawmDataSection = new ArrayList<String>();
hMap = new HashMap();
managedDataArray = new ArrayList<Data> ();
organizedData = new ArrayList<ArrayList<String>>();
mData.add("2016-05-3");
mData.add("2016-04-3");
mData.add("2016-02-3");
mData.add("2015-12-3");
for (int i = 0 ; i<mData.size() && i<mData.size() ; i++ ){
//spilting the data
String string = mData.get(i);
String[] parts = string.split("-");
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
RawmDataSection.add(part1);
}
Set<String> uniqueSet = new HashSet<String>(RawmDataSection);
mDataSection.addAll(uniqueSet);
final List<Data> data = new ArrayList<>();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "ReFreshing", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
Data dataObject = new Data();
for (int i = 0; i < mData.size(); i++) {
dataObject.RowMonth = mData.get(i);
Log.d("row :" + mData.get(i), " Section : ");
data.add(dataObject);
}
for (int i = 0; i < mDataSection.size(); i++) {
dataObject.SectionYear = mDataSection.get(i);
Log.d("row :", " Section : " + mDataSection.get(i));
data.add(dataObject);
}
recyclerView = (RecyclerView) findViewById(R.id.List);
MainAdapter adapter = new MainAdapter(MainActivity.this, mData, mDataSection);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
recyclerView.setHasFixedSize(true);
organizedData.add(mDataSection);
organizedData.add(mData);
}
});
}
}
i even don't know where to start so if any body can give me any hint or guidance than it'll be so helpful and highly appreciated by me , thanks
if my question is not understandable then please let me know i'll fix it

You can achieve that in a simpler way with the library SectionedRecyclerViewAdapter.
First create a Section class to group your items:
class MySection extends StatelessSection {
String title;
List<String> list;
public MySection(String title, List<String> list) {
// call constructor with layout resources for this Section header, footer and items
super(R.layout.section_header, R.layout.section_item);
this.title = title;
this.list = list;
}
#Override
public int getContentItemsTotal() {
return list.size(); // number of items of this section
}
#Override
public RecyclerView.ViewHolder getItemViewHolder(View view) {
// return a custom instance of ViewHolder for the items of this section
return new MyItemViewHolder(view);
}
#Override
public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) {
MyItemViewHolder itemHolder = (MyItemViewHolder) holder;
// bind your view here
itemHolder.tvItem.setText(list.get(position));
}
#Override
public RecyclerView.ViewHolder getHeaderViewHolder(View view) {
return new SimpleHeaderViewHolder(view);
}
#Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) {
MyHeaderViewHolder headerHolder = (MyHeaderViewHolder) holder;
// bind your header view here
headerHolder.tvItem.setText(title);
}
}
Then you set up the RecyclerView with your Sections:
// Create an instance of SectionedRecyclerViewAdapter
SectionedRecyclerViewAdapter sectionAdapter = new SectionedRecyclerViewAdapter();
// Create your sections with the list of data for each year
MySection section2015 = new MySection("2015", dataList2015);
MySection section2016 = new MySection("2016", dataList2016);
// Add your Sections to the adapter
sectionAdapter.addSection(section2015);
sectionAdapter.addSection(section2016);
// Set up your RecyclerView with the SectionedRecyclerViewAdapter
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(sectionAdapter);

Related

I need help regrading deleting items inside RecyclerView. Deletion works but updating RecyclerView sometimes doesn't work after deletion

Sometimes delete function works sometimes not. I think the problem is with the notifyItemRemove or removing items inside the array. Worked on finding the bug for 3 days but in vain.
This is the adapter class
public class ChecklistItems extends AppCompatActivity {
Toolbar toolbar;
RecyclerView recyclerView;
String content;
String status;
String[] contentSplit;
String[] statusSplit;
private ChecklistAdapter checklistAdapter;
DbHelper dbHelper;
List<ChecklistHelper> checks;
int id;
ChecklistHelper checklistHelper;
StringBuilder stringBuilderContent;
StringBuilder stringBuilderStatus;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checklist_items);
toolbar = findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
recyclerView = findViewById(R.id.recycler_view_child);
id = getIntent().getIntExtra("id", 0);
content = getIntent().getStringExtra("content");
status = getIntent().getStringExtra("status");
contentSplit = content.split("\n");
statusSplit = status.split("\n");
checklistHelper = new ChecklistHelper();
dbHelper = new DbHelper(this);
checks = dbHelper.getChecklists();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
checklistHelper = dbHelper.getChecklists(id);
String status = checklistHelper.getStatus();
String[] statusSplit = status.split("\n");
ArrayList<String> newStatusList = new ArrayList<>(Arrays.asList(statusSplit));
ArrayList<String> newContentList = new ArrayList<>(Arrays.asList(statusSplit));
checklistAdapter = new ChecklistAdapter(newStatusList, newContentList);
recyclerView.setAdapter(checklistAdapter);
}
public class ChecklistAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
ArrayList<String> newStatusList;
ArrayList<String> newContentList;
public ChecklistAdapter( ArrayList<String> newStatusList, ArrayList<String> newContentList) {
this.newStatusList = newStatusList;
this.newContentList = newContentList;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.checklist_layout_child, parent, false);
return new ChecklistChildViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, #SuppressLint("RecyclerView") int position) {
ChecklistChildViewHolder checklistChildViewHolder = (ChecklistChildViewHolder) holder;
checklistChildViewHolder.checkBox.setText(contentSplit[position]);
boolean state;
if (statusSplit[position].equals("1")) {
state = true;
checklistChildViewHolder.checkBox.setText(lineThrough(checklistChildViewHolder.checkBox.getText().toString()));
}
else
{
state = false;
checklistChildViewHolder.checkBox.setText(checklistChildViewHolder.checkBox.getText().toString());
}
checklistChildViewHolder.checkBox.setChecked(state);
checklistChildViewHolder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
doDelete(position);
}
});
}
#Override
public int getItemCount() {
return newStatusList.size();
}
public class ChecklistChildViewHolder extends RecyclerView.ViewHolder {
CheckBox checkBox;
ImageView delete, edit;
ChecklistChildViewHolder(#NonNull View itemView) {
super(itemView);
checkBox = itemView.findViewById(R.id.checkbox_child);
delete = itemView.findViewById(R.id.delete_child);
edit = itemView.findViewById(R.id.edit_child);
delete.setVisibility(View.INVISIBLE);
edit.setVisibility(View.INVISIBLE);
}
public void updateVisibility(boolean isEnableDelete){
if (isEnableDelete) {
delete.setVisibility(View.VISIBLE);
edit.setVisibility(View.VISIBLE);
}
else {
delete.setVisibility(View.INVISIBLE);
edit.setVisibility(View.INVISIBLE);
}
}
}
public int doDelete(int position) {
int idd = getIntent().getIntExtra("id", 0);
checklistHelper = dbHelper.getChecklists(idd);
String status = checklistHelper.getStatus();
String content = checklistHelper.getContent();
String[] statusSplit = status.split("\n");
String[] contentSplit = content.split("\n");
newStatusList = new ArrayList<>(Arrays.asList(statusSplit));
newContentList = new ArrayList<>(Arrays.asList(contentSplit));
newStatusList.remove(position);
newContentList.remove(position);
stringBuilderStatus = new StringBuilder();
stringBuilderContent = new StringBuilder();
for(String singleStatus : newStatusList) {
stringBuilderStatus.append(singleStatus);
stringBuilderStatus.append("\n");
}
for(String singleContent: newContentList){
stringBuilderContent.append(singleContent);
stringBuilderContent.append("\n");
}
String allStatus = stringBuilderStatus.toString();
String allContent = stringBuilderContent.toString();
dbHelper.updateChecklist(id,allStatus , allContent, DateTime.date(), DateTime.time(), System.currentTimeMillis());
if(allContent.length()==0) {
dbHelper.deleteChecklist(id);
finish();
}
notifyItemRemoved(position);
notifyItemChanged(position);
return newStatusList.size();
}
}
}
I have used most of the (notify) functions which update the RecyclerView but none worked properly.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checklist_items);
toolbar = findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
recyclerView = findViewById(R.id.recycler_view_child);
id = getIntent().getIntExtra("id", 0);
content = getIntent().getStringExtra("content");
status = getIntent().getStringExtra("status");
contentSplit = content.split("\n");
statusSplit = status.split("\n");
checklistHelper = new ChecklistHelper();
dbHelper = new DbHelper(this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(checklistAdapter);
checklistHelper = dbHelper.getChecklists(id);
String status = checklistHelper.getStatus();
String[] statusSplit = status.split("\n");
ArrayList<String> newStatusList = new ArrayList<>(Arrays.asList(statusSplit));
ArrayList<String> newContentList = new ArrayList<>(Arrays.asList(statusSplit));
checklistAdapter = new ChecklistAdapter(newStatusList, newContentList);
recyclerView.setAdapter(checklistAdapter);
}
Your problem is notifyItemChanged(position);. When you remove an item, you are changing the position of all other items beyond it.
You want to use notifyItemRangeChanged(position, newContentList.size()); as this will take into account the shifting positions.
You use notifyItemChanged(position); if the content of the position has changed, but the position it self remains the same.
you need to remove the lines in doDelete method:
newStatusList = new ArrayList<>(Arrays.asList(statusSplit));
newContentList = new ArrayList<>(Arrays.asList(contentSplit));
two lines will re-assign the new object and the underlay data may not locate in the same memory position as the old newStatusList and newContentList
And you can use Adapter.notifyDataSetChanged() instead of notifyItemXXX
The solution for my problem is not to use position variable which provided inside onBindViewHolder but instead use holder.getLayoutPosition or holder.getLayoutPosition. That is working for me.

How to display multiple recycler views on Android Studio?

very new to Android App development here. I'm not sure if I'm asking the right question, but here's my situation. I have a simple gradebook app that looks like the following:
My goal is to display multiple courses on the app. I am using the RecyclerView to implement this, using the following onCreate function in my activity to pass the course information to the adapter:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grade);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
for(int i = 0; i<2; i++)
{
Course course = Course.generateRandomCourse();
recyclerView = (RecyclerView) findViewById(R.id.togglegrades);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
mAdapter = new RecyclerViewAdapter(course);
recyclerView.setAdapter(mAdapter);
}
My goal for the for loop was to have two courses show up, but this is not the case. I'm not sure whether I need to rework my Recycling Adapter to take a list of courses, or if there is a simple way to display multiple courses.
Any help is much appreciated! Thank you for your time :)
EDIT: After adding 2 recyclers in XML and trying to invoke both, this is the code I used:
Course course = Course.generateRandomCourse();
Course course1 = Course.generateRandomCourse();
recyclerView = (RecyclerView) findViewById(R.id.togglegrades);
recyclerView1 = (RecyclerView) findViewById(R.id.togglegrades1);
layoutManager = new LinearLayoutManager(this);
layoutManager1 = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView1.setLayoutManager(layoutManager1);
mAdapter = new RecyclerViewAdapter(course);
mAdapter1 = new RecyclerViewAdapter(course1);
recyclerView.setAdapter(mAdapter);
recyclerView1.setAdapter(mAdapter1);
Now the output is just overlapped.
EDIT 2: Including full adapter code below.
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
{
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
private List<Course> courses = new ArrayList<>();
private ArrayList<Assignment> assignments;
private String course;
private String average;
public RecyclerViewAdapter(List<Course> courses)
{
for(Course c : courses)
{
course = c.getCourseTitle();
assignments = c.getAssignments();
if(assignments.size()==0)
{
average = "0";
}
else
{
Integer grade_total = new Integer(0);
Integer assignment_total = new Integer(0);
for (Assignment i : assignments)
{
grade_total += i.getAssignmentGrade();
assignment_total++;
}
average = Integer.toString(grade_total /assignment_total);
}
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,int viewType)
{
if(viewType == TYPE_HEADER)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.header_course,parent,false);
return new ViewHolderHeader(v);
}
else if(viewType == TYPE_ITEM)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_course, parent, false);
return new ViewHolderItem(v);
}
else return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
if(holder instanceof ViewHolderHeader)
{
ViewHolderHeader VHHeader = (ViewHolderHeader)holder;
VHHeader.title.setText(course);
VHHeader.average.setText("Average: " + average + "%");
}
else if(holder instanceof ViewHolderItem)
{
String assignemnt_name = assignments.get(position-1).getAssignmentTitle();
String assignment_grade = Integer.toString(assignments.get(position-1).getAssignmentGrade());
ViewHolderItem VHItem = (ViewHolderItem)holder;
VHItem.name.setText(assignemnt_name);
VHItem.grade.setText(assignment_grade + "%");
}
}
#Override
public int getItemCount()
{
return assignments.size() + 1;
}
private boolean isPositionHeader(int position)
{
if(position == 0)
return true;
else
return false;
}
#Override
public int getItemViewType(int position)
{
if(isPositionHeader(position))
return TYPE_HEADER;
return TYPE_ITEM;
}
public class ViewHolderHeader extends RecyclerView.ViewHolder
{
TextView title;
TextView average;
public ViewHolderHeader(View view)
{
super(view);
this.title = (TextView)itemView.findViewById(R.id.course);
this.average = (TextView)itemView.findViewById(R.id.average);
}
}
public class ViewHolderItem extends RecyclerView.ViewHolder
{
TextView name;
TextView grade;
public ViewHolderItem(View view)
{
super(view);
this.name = (TextView)itemView.findViewById(R.id.assignment);
this.grade = (TextView)itemView.findViewById(R.id.grade);
}
}
}
You do not need to use multiple RecyclerView.
Just look at your code and you will find the answer why your code is not working.
RecyclerView is similar like listview where you have to pass a list. But in your code you are passing just 1 object of course.
You must not add recyclerview inside for loop, as recyclerview purpose is to store list,not 1 object.
So you should pass List to the recyclerview.
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grade);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
recyclerView = (RecyclerView) findViewById(R.id.togglegrades);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
List<Course> listCourse=new ArrayList();
for(int i = 0; i<2; i++)
{
listCourse.add(Course.generateRandomCourse());
}
mAdapter = new RecyclerViewAdapter(listCourse);
recyclerView.setAdapter(mAdapter);
}
And inside the adapter you can use this list of course.
For more reference you can check this link, on how to use RecyclerView with Adapter
EDIT: In your adapter look at this code:
private boolean isPositionHeader(int position)
{
if(position == 0)
return true;
else
return false;
}
Here position == 0 is static code, which will not work for dynamic code.If your list contains 1 Header and 1 Item, than you can change simply position%2 == 0 condition. else you have to create other recyclerview inside adapter.
Check out below code and comments I have added , at the end of onBindViewHolder you can add new recyclerview, for that you have to add recyclerview in your layout also.
Checkout how you can use List<Course> courses in your constructor and onBindViewHolder.
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
private List<Course> courses = new ArrayList<>();
public RecyclerViewAdapter(List<Course> courses)
{
this.courses = courses;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,int viewType)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.header_course,parent,false);
return new ViewHolderHeader(v);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
Course c=courses.get(position);
String course = c.getCourseTitle();
String assignments = c.getAssignments();
if(assignments.size()==0)
{
average = "0";
}
else
{
Integer grade_total = new Integer(0);
Integer assignment_total = new Integer(0);
for (Assignment i : assignments)
{
grade_total += i.getAssignmentGrade();
assignment_total++;
}
average = Integer.toString(grade_total /assignment_total);
}
ViewHolderHeader VHHeader = (ViewHolderHeader)holder;
VHHeader.title.setText(course);
VHHeader.average.setText("Average: " + average + "%");
//Here you can set new recyclerview in your adapter for assignments
}
#Override
public int getItemCount()
{
return courses.size();
}
/*private boolean isPositionHeader(int position)
{
//Change logic here as per your list, because you have list not single object.
//if(position == 0)
// return true;
//else
// return false;
}*/
//Remove this code as you have not different views in your list
/*#Override
public int getItemViewType(int position)
{
if(isPositionHeader(position))
return TYPE_HEADER;
return TYPE_ITEM;
}*/
public class ViewHolderHeader extends RecyclerView.ViewHolder
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.header_course,parent,false);
return new ViewHolderHeader(v);
}
}
You need to have 2 RecycleViews in your activity_grade xml layout, and do what you're doing inside the for loops for each.
What your for loop is currently doing, is creating a random course, and then setting that course to the RecyclerView called togglegrades, then on the second iteration, it does the same thing again, on the same RecyclerView
So what I would do after adding a second RecyclerView in the xml layout, is replace the for loop with something like this:
recyclerView1 = (RecyclerView) findViewById(R.id.togglegrades);
recyclerView2 = (RecyclerView) findViewById(R.id.togglegrades2);
layoutManager = new LinearLayoutManager(this);
recyclerView1.setLayoutManager(layoutManager);
recyclerView2.setLayoutManager(layoutManager);
mAdapter = new RecyclerViewAdapter(course);
// Maybe create a different course here and set it to a new adapter variable
recyclerView.setAdapter(mAdapter);
recyclerView2.setAdapter(mAdapter);
You can do it in a very optimal way. Please see the tutorial titled Recyclerview multiple view type. Here you don't need to create multiple recycler views and you can use a single recycler view for multiple types of data.
Why do you use two RecyclerView?
Your Layout looks simple, just use one recyclerView with two viewType.
This is a sample

How to get total by adding all the recycler views rows

I have recycler view in my activity and below there is a total cost field which shows the total value comes after adding the values from each row. As shown in the screen below:
In a recycler view, there is a spinner that shows quantity on selecting a value from spinner it will be multiplied by the MRP like this every same row have some values. I want to add this value and want to show it in the Lower left corner.
So far I am sending MRP value from adapter class to activity using LocalBroadcatManager class.
But every time I selecting data from another row it does not add cost with the previous value
but it replaces the older value.
Below is my code:
ProductAdapter.java
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ViewHolder> {
private Context context;
private List<ProductsModel> productList;
public ProductAdapter(Context context, List<ProductsModel> productList) {
this.context = context;
this.productList = productList;
}
#NonNull
#Override
public ProductAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.selectpack_layout,parent,false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull final ProductAdapter.ViewHolder holder, int position) {
final ProductsModel model = productList.get(position);
holder.marketName.setText(model.getMarketName());
holder.productNo.setText(model.getProductNo());
holder.page.setText(model.getPage());
holder.mrp.setText(model.getMrp());
holder.innerPack.setText(model.getInnerPack());
holder.outerPack.setText(model.getOuterPack());
List<String> qty = new ArrayList<>();
qty.add("Select qty");
qty.add("1");
qty.add("2");
qty.add("3");
qty.add("4");
qty.add("5");
qty.add("6");
qty.add("7");
qty.add("8");
qty.add("9");
qty.add("10");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, qty);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.qtySpinner.setAdapter(dataAdapter);
holder.qtySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
int sum = 0;
String item = adapterView.getItemAtPosition(i).toString();
if (!item.equals("Select qty")) {
int qty = Integer.parseInt(item);
int cost = Integer.parseInt(model.getMrp());
int val = cost * qty;
holder.total.setText(String.valueOf(val));
Intent intent = new Intent("msg");
intent.putExtra("cost", String.valueOf(val));
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public int getItemCount() {
return productList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView marketName,productNo,page,mrp,innerPack,outerPack,total;
Spinner qtySpinner;
Button order;
public ViewHolder(#NonNull View itemView) {
super(itemView);
order = itemView.findViewById(R.id.order);
qtySpinner = itemView.findViewById(R.id.qtySpinner);
marketName = itemView.findViewById(R.id.marketName);
productNo = itemView.findViewById(R.id.productNo);
page = itemView.findViewById(R.id.page);
mrp = itemView.findViewById(R.id.mrp);
innerPack = itemView.findViewById(R.id.innerPack);
outerPack = itemView.findViewById(R.id.outerPack);
total = itemView.findViewById(R.id.total);
}
}
}
SelectPack.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_pack);
fAuth = FirebaseAuth.getInstance();
ActionBar ab = getSupportActionBar();
assert ab!= null;
ab.setTitle("Select Pack");
ab.setDisplayHomeAsUpEnabled(true);
marketSpinner = findViewById(R.id.marketSpinner);
progress = findViewById(R.id.progress);
products = findViewById(R.id.products);
totalCost = findViewById(R.id.totalCost);
products.setHasFixedSize(true);
products.setLayoutManager(new LinearLayoutManager(this));
productList = new ArrayList<>();
List<String> categories = new ArrayList<String>();
categories.add("Select market");
categories.add("Crown");
categories.add("Long Book A4");
categories.add("Long Book");
categories.add("Crown Junior");
categories.add("Physics");
categories.add("Chemistry");
categories.add("Biology");
categories.add("Universal");
categories.add("Sketch Book");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
marketSpinner.setAdapter(dataAdapter);
marketSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String item = adapterView.getItemAtPosition(i).toString();
if(item.equals("Select market")){
progress.setVisibility(View.INVISIBLE);
}
else{
getData(item);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
LocalBroadcastManager.getInstance(SelectPack.this).registerReceiver(message,new IntentFilter("msg"));
}
private void getData(String item){
progress.setVisibility(View.VISIBLE);
products.setVisibility(View.INVISIBLE);
productList.clear();
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(20,TimeUnit.SECONDS)
.writeTimeout(20,TimeUnit.SECONDS)
.build();
RequestBody formBody = new FormBody.Builder()
.add("name",item)
.build();
Request request = new Request.Builder().post(formBody).url(URL).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onResponse(#NotNull Call call, #NotNull final Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONArray jsonArray = new JSONArray(response.body().string());
if(jsonArray.length() > 0){
products.setVisibility(View.VISIBLE);
progress.setVisibility(View.INVISIBLE);
}
for(int i=0;i<jsonArray.length();i++){
progress.setVisibility(View.INVISIBLE);
JSONObject object = jsonArray.getJSONObject(i);
String str1 = object.getString("market");
String str2 = object.getString("product_no");
String str3 = object.getString("page");
String str4 = object.getString("mrp");
String str5 = object.getString("inner_pack");
String str6 = object.getString("outer_pack");
Log.d("prod",str2);
ProductsModel model = new ProductsModel(str1,str2,str3,str4,str5,str6);
productList.add(model);
}
ProductAdapter adapter = new ProductAdapter(getApplicationContext(),productList);
products.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
#Override
public void onFailure(#NotNull Call call, #NotNull final IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
progress.setVisibility(View.INVISIBLE);
products.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
});
}
public BroadcastReceiver message = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String nam = intent.getStringExtra("cost");
if(nam != null){
int val = Integer.parseInt(nam);
totalCost.setText("Total: "+val+".00");
}
}
};
Someone, please let me know what I am doing wrong or how should I implement it correctly. Any help would be appreciated.
THANKS
why you are using local broadcasts to communicate with activity. Instead, use interface to communicate it will be easy to use.
I found the problem when the item is getting selected you are passing the only current value not all the selected value that's why it is showing the latest value instead of all the value.
You should pass all the selected values from the list, let's say If I select one value, keep that in the separate list or you can manage with a flag in the current list object and when user selects any item then loop through that list and add all the price and pass it to activity.
Add one field in ProductsModel called Qty
Here is my updated adapter class I have added a comment as well please try this Hope it helps
public class ProductAdapter extends RecyclerView.Adapter {
private Context context;
private List<ProductsModel> productList;
// add this list
private List<ProductsModel> selectedProductList = new ArrayList();
public ProductAdapter(Context context, List<ProductsModel> productList) {
this.context = context;
this.productList = productList;
}
#NonNull
#Override
public ProductAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.selectpack_layout,parent,false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull final ProductAdapter.ViewHolder holder, int position) {
final ProductsModel model = productList.get(position);
holder.marketName.setText(model.getMarketName());
holder.productNo.setText(model.getProductNo());
holder.page.setText(model.getPage());
holder.mrp.setText(model.getMrp());
holder.innerPack.setText(model.getInnerPack());
holder.outerPack.setText(model.getOuterPack());
List<String> qty = new ArrayList<>();
qty.add("Select qty");
qty.add("1");
qty.add("2");
qty.add("3");
qty.add("4");
qty.add("5");
qty.add("6");
qty.add("7");
qty.add("8");
qty.add("9");
qty.add("10");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, qty);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.qtySpinner.setAdapter(dataAdapter);
holder.qtySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
int sum = 0;
String item = adapterView.getItemAtPosition(i).toString();
// add this line
adapterView.getItemAtPosition(i);
if (!item.equals("Select qty")) {
// add this line
model.setQty(Integer.parseInt(item));
selectedProductList.add(model);
}
int val = 0;
for(int j = 0; j < selectedProductList.size(); j++){
ProductsModel model = selectedProductList.get(i);
int mrp = model.getMrp();
int qty = model.getQty();
val = val + (mrp * qty);
}
holder.total.setText(String.valueOf(val));
Intent intent = new Intent("msg");
intent.putExtra("cost", String.valueOf(val));
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public int getItemCount() {
return productList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView marketName,productNo,page,mrp,innerPack,outerPack,total;
Spinner qtySpinner;
Button order;
public ViewHolder(#NonNull View itemView) {
super(itemView);
order = itemView.findViewById(R.id.order);
qtySpinner = itemView.findViewById(R.id.qtySpinner);
marketName = itemView.findViewById(R.id.marketName);
productNo = itemView.findViewById(R.id.productNo);
page = itemView.findViewById(R.id.page);
mrp = itemView.findViewById(R.id.mrp);
innerPack = itemView.findViewById(R.id.innerPack);
outerPack = itemView.findViewById(R.id.outerPack);
total = itemView.findViewById(R.id.total);
}
}
}

RecyclerView OutOfBoundsException When No Items in Array

I am trying to create a RecyclerView that populates CardViews based on data in Firebase. I am receiving an IndexOutOfBoundsException when there is no data in Firebase, however I would like for the RecyclerView to display (without any data) when there is no data in Firebase:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Firebase.setAndroidContext(this);
setContentView(R.layout.activity_discussion);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
setTitle(R.string.discussion_title_text);
mDateFormat = new SimpleDateFormat("MM-dd-yyyy");
mDate = new Date();
mCurrentDateString = mDateFormat.format(mDate);
mBaseRef = new Firebase(FIREBASE_URL);
mPollsRef = mBaseRef.child(POLLS_LABEL);
mUpdateRef = mPollsRef.child(mCurrentDateString).child(String.valueOf(mPollIndex + 1));
mCommentsRef = mUpdateRef.child(COMMENTS_LABEL);
mPollImage = (ImageView) findViewById(R.id.comments_image);
mPollCommentQuestion = (TextView) findViewById(R.id.poll_comment_question);
mUserComment = (EditText) findViewById(R.id.user_comment);
mUserAvatar = (ImageView) findViewById(R.id.profile_image_avatar);
mCommentArrayList = new ArrayList<Comments>();
mCommentIDArrayList = new ArrayList<String>();
mPollCommentsList = (RecyclerView) findViewById(R.id.poll_comments_list);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
mPollCommentsList.setLayoutManager(llm);
mPollCommentsList.setHasFixedSize(true);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
mUpdateRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
setImage(dataSnapshot);
setQuestion(dataSnapshot);
createInitialCommentIDArray(dataSnapshot);
mNumberOfCommentsAtPoll = (int) dataSnapshot.child(COMMENTS_LABEL).getChildrenCount();
for (int i = 0; i < mNumberOfCommentsAtPoll; i++) {
String commentID = (String) dataSnapshot.child(COMMENTS_LABEL).child(mCommentIDArrayList.get(i)).child("COMMENT").getValue();
Log.v("COMMENT_ID", "The comment ID is " + commentID);
String userID = (String) dataSnapshot.child(COMMENTS_LABEL).child(mCommentIDArrayList.get(i)).child("USER_ID").getValue();
Log.v("USER_ID", "The user ID is " + userID);
mCommentArrayList.add(0, new Comments(mUserAvatar, userID, commentID));
mCommentAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
mCommentAdapter = new MyAdapter(mCommentArrayList);
mPollCommentsList.setAdapter(mCommentAdapter);
Intent intent = getIntent();
String pollID = intent.getStringExtra("POLL_ID");
mPollIndex = intent.getIntExtra("POLL_INDEX", 0);
//TODO: Store unique comment ID's in an array
//TODO: Figure out how to programmatically add images to AWS and then store URL in Firebase
ImageView fab = (ImageView) findViewById(R.id.add_comment);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
HashMap<String, Object> commentMap = new HashMap<String, Object>();
commentMap.put("USER_ID", mBaseRef.getAuth().getUid());
commentMap.put("COMMENT", mUserComment.getText().toString());
mUpdateRef.child(COMMENTS_LABEL).push().updateChildren(commentMap);
hideKeyboard(view);
mUserComment.setText("");
Toast.makeText(getApplicationContext(), R.string.comment_added, Toast.LENGTH_LONG).show();
}
});
}
My Array Adapter, I note where the error is occurring:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<Comments> mDataSet;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
protected ImageView userAvatar;
protected TextView userID;
protected TextView userComment;
public ViewHolder(View v) {
super(v);
userAvatar = (ImageView) findViewById(R.id.profile_image_avatar);
userID = (TextView) findViewById(R.id.user_ID);
userComment = (TextView) findViewById(R.id.user_comment);
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(ArrayList<Comments> myDataset) {
mDataSet = myDataset;
}
// Create new views (invoked by the layout manager)
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.individual_comment, parent, false);
// set the view's size, margins, paddings and layout parameters
ViewHolder x = new ViewHolder(v);
return x;
}
// Replace the contents of a view (invoked by the layout manager)
//The OutOfBoundsException is pointing here
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.userComment.setText(mCommentArrayList.get(position).getUserComment());
String x = mCommentArrayList.get(position).getUserComment();
Log.v("ON_BIND_VIEW", "THE STRING IS " + x);
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mNumberOfCommentsAtPoll;
}
}
Result:
You should try to return mDataset.size() in the getItemCount() method instead of mNumberOfCommentsAtPoll.
#Override
public int getItemCount() {
return mDataSet.size();
}

SectionedRecyclerView over Write first item

I'm Trying to use : SimpleSectionedRecyclerViewAdapter , i have arrayList that have 30 elements with strings , i'm going to group every 10 elements with header Title ,
first item should be "Item0" with header name "First 10 elements start"
but when doing that i get :
"First 10 elements start" // header titile
"Item1" <---! note : it should "Item0"
so where is index number 0 gone?
//adapter.addItem3(CategoriesList.get(0));
List<SimpleSectionedRecyclerViewAdapter.Section> sections =
new ArrayList<SimpleSectionedRecyclerViewAdapter.Section>();
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(0, "First 10 elements start"));
//Add your adapter to the sectionAdapter
SimpleSectionedRecyclerViewAdapter.Section[] dummy = new SimpleSectionedRecyclerViewAdapter.Section[sections.size()];
SimpleSectionedRecyclerViewAdapter mSectionedAdapter = new
SimpleSectionedRecyclerViewAdapter(activity, R.layout.drawer_header_book, R.id.headerName, adapter);
mSectionedAdapter.setSections(sections.toArray(dummy));
mDrawerList.setLayoutManager(new LinearLayoutManager(activity));
mDrawerList.setAdapter(mSectionedAdapter);
I'm using exactly as adapter :
https://gist.github.com/gabrielemariotti/4c189fb1124df4556058
public class DrawerItemCustomAdapterForAllBooks extends RecyclerView.Adapter<DrawerItemCustomAdapterForAllBooks.SimpleViewHolder> {
private final Context context;
Typeface custom_font;
ArrayList<Categories> mData;
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
int BookID;
public void add(Categories s,int position) {
position = position == -1 ? getItemCount() : position;
mData.add(position,s);
notifyItemInserted(position);
}
public void remove(int position){
if (position < getItemCount() ) {
mData.remove(position);
notifyItemRemoved(position);
}
}
public DrawerItemCustomAdapterForAllBooks(Context context, ArrayList<Categories> Categories2, int BookID) {
this.mData = Categories2;
this.context = context;
this.BookID = BookID;
custom_font = Typeface.createFromAsset(context.getAssets(), "fonts/HelveticaNeueLTArabic-Light.ttf");
}
public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(context).inflate(R.layout.listview_item_row, parent, false);
return new SimpleViewHolder(view);
}
#Override
public void onBindViewHolder(SimpleViewHolder holder, final int position) {
if (holder != null) {
final Categories currentItem = getItem(holder.getAdapterPosition());
SimpleViewHolder genericViewHolder = (SimpleViewHolder) holder;
genericViewHolder.position = holder.getAdapterPosition();
genericViewHolder.CategoryName.setText(currentItem.getName());
genericViewHolder.CategoryName.setTypeface(custom_font);
genericViewHolder.CategoryName.setTag(holder.getAdapterPosition());
genericViewHolder.itemView.setTag(holder.getAdapterPosition());
if (currentItem.getBookID() == 1) {
genericViewHolder.CategoryName.setTextColor(context.getResources().getColor(R.color.nokhba_white));
genericViewHolder.itemView.setBackgroundColor(context.getResources().getColor(R.color.nokhba_darkrose));
Picasso.with(context).load(R.drawable.list_icon_e02)
.error(R.drawable.no_internet)
.tag(context)
.placeholder(R.drawable.no_spic)
.into(genericViewHolder.CategoryImage);
} else if (currentItem.getBookID() == 2) {
genericViewHolder.itemView.setBackgroundColor(context.getResources().getColor(R.color.nokhba_openrose));
genericViewHolder.CategoryName.setTextColor(context.getResources().getColor(R.color.nokhba_darkrose));
Picasso.with(context).load(R.drawable.list_icon_08)
.error(R.drawable.no_internet)
.tag(context)
.placeholder(R.drawable.no_spic)
.into(genericViewHolder.CategoryImage);
} else if (currentItem.getBookID() == 3) {
genericViewHolder.CategoryName.setTextColor(context.getResources().getColor(R.color.nokhba_darkrose));
genericViewHolder.itemView.setBackgroundColor(context.getResources().getColor(R.color.nokhba_white));
Picasso.with(context).load(R.drawable.list_icon_08)
.error(R.drawable.no_internet)
.tag(context)
.placeholder(R.drawable.no_spic)
.into(genericViewHolder.CategoryImage);
}
}
}
#Override
public int getItemCount() {
return mData.size()-2;
}
public Categories getItem(int position) {
return mData.get(position-1);
}
public static class SimpleViewHolder extends RecyclerView.ViewHolder {
protected TextView CategoryName;
protected ImageView CategoryImage;
protected View itemView;
int position = -1;
public SimpleViewHolder(View itemView) {
super(itemView);
this.CategoryName = (TextView) itemView.findViewById(R.id.CategoryName);
this.CategoryImage = (ImageView) itemView.findViewById(R.id.CategoryImage);
// CategoryName.setTypeface(custom_font);
this.itemView = itemView;
getAdapterPosition();
this.CategoryName = (TextView) itemView.findViewById(R.id.CategoryName);
this.CategoryImage = (ImageView) itemView.findViewById(R.id.CategoryImage); }
}
}
With the library SectionedRecyclerViewAdapter you can group your items in sections and add a header to each section without worrying about the "position" of the headers:
class MySection extends StatelessSection {
String title;
List<Categories> list;
public MySection(String title, List<Categories> list) {
// call constructor with layout resources for this Section header, footer and items
super(R.layout.section_header, R.layout.section_item);
this.title = title;
this.list = list;
}
#Override
public int getContentItemsTotal() {
return list.size(); // number of items of this section
}
#Override
public RecyclerView.ViewHolder getItemViewHolder(View view) {
// return a custom instance of ViewHolder for the items of this section
return new MyItemViewHolder(view);
}
#Override
public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) {
MyItemViewHolder itemHolder = (MyItemViewHolder) holder;
// bind your view here
itemHolder.tvItem.setText(list.get(position).getName());
}
#Override
public RecyclerView.ViewHolder getHeaderViewHolder(View view) {
return new SimpleHeaderViewHolder(view);
}
#Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) {
MyHeaderViewHolder headerHolder = (MyHeaderViewHolder) holder;
// bind your header view here
headerHolder.tvItem.setText(title);
}
}
Then you set up the RecyclerView with your Sections:
// Create an instance of SectionedRecyclerViewAdapter
SectionedRecyclerViewAdapter sectionAdapter = new SectionedRecyclerViewAdapter();
// Create your sections with a sub list of data from mData
MySection data1Section = new MySection("First 10 elements start", categories1List);
MySection data2Section = new MySection("Elements from 10 to 20 start", categories2List);
MySection data3Section = new MySection("Elements from 20 to 30 start", categories3List);
// Add your Sections to the adapter
sectionAdapter.addSection(data1Section);
sectionAdapter.addSection(data2Section);
sectionAdapter.addSection(data3Section);
// Set up your RecyclerView with the SectionedRecyclerViewAdapter
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(sectionAdapter);

Categories