How to access database from RecyclerView Adapter holder?

436 views Asked by At

I'm in need of advice on how to get data from the database, or whatever approach is best, from a RecyclerView adapter onBindViewHolder() method. Basically I have a list of Transactions that the ViewHolder cycles through, which contains an ID for a related entity called Payee, which I can obtain by accessing the Transaction's getPayeeByID method. (That method already exists to pull the info in the repository and Dao and works fine.) The problem is, how do I access that method from this screen? I need to know how get to it from here so I can create a new Payee based on the pulled PayeeId, in order to set the holder.payee.setText field with the name of the associated Payee. I have no idea how to do that from here.

 @Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

    final Transaction transaction = tTransactions.get(holder.getAdapterPosition());


   holder.payee.setText( ????????? ) ;        
   holder.date.setText(date);
   holder.transAmount.setText(amount);

I am happy to add more code if needed.

1

There are 1 answers

0
TDawg On

I realized the solution to this. I just created an instance of the repository and accessed the DB through that. See below:

 AppRepository repository = new AppRepository(tContext);

 final Payee payee = repository.getPayeeById(transaction.getPayeeId());

 holder.payee.setText(payee.getName());