I'm trying to display data with a RecyclerView
. I'm not too sure why it keep crashing with a NullPointerException
. My theory is that it is trying to find the TextView
before the view itself has been created.
However, with the way my constructor is, it shouldn't be doing that.
Been at this for a couple hours now. Any help would be greatly appreciated.
My XML file:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
>
<TextView
android:id="@+id/recycler_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="name"
android:textColor="@color/icons" />
<TextView
android:id="@+id/recycler_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="18dp"
android:text="price"
android:textColor="@color/icons"
android:textStyle="bold"/>
<TextView
android:id="@+id/recycler_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="date"
android:layout_below="@+id/recycler_name"
android:textColor="@color/icons"
android:textStyle="italic"
android:paddingTop="3dp"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>
RecyclerView Adapter:
public class ExpenseAdapter extends RecyclerView.Adapter<ExpenseAdapter.ItemViewHolder> {
private ArrayList<Item> mExpenseList;
public static class ItemViewHolder extends RecyclerView.ViewHolder {
public TextView frag_name;
public TextView frag_price;
public TextView frag_date;
public ItemViewHolder(@NonNull View itemView) {
super(itemView);
frag_name.findViewById(R.id.recycler_name);
frag_price.findViewById(R.id.recycler_price);
frag_date.findViewById(R.id.recycler_date);
}
}
@NonNull
@Override
public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.expense, parent, false);
ItemViewHolder viewHolder = new ItemViewHolder(v);
return viewHolder;
}
// constructor to receive list of expenses for recycler view to process
public ExpenseAdapter(ArrayList<Item> expenseList) {
mExpenseList = expenseList;
}
@Override
public void onBindViewHolder(@NonNull ItemViewHolder itemViewHolder, int i) {
Item currItem = mExpenseList.get(i);
itemViewHolder.frag_name.setText(currItem.getName());
itemViewHolder.frag_price.setText(Integer.toString(currItem.getPrice()));
itemViewHolder.frag_date.setText(currItem.getDatePurhase());
}
@Override
public int getItemCount() {
return mExpenseList.size();
}
}