Sunday, 2 May 2021

android: load List from Room using CompletableFuture?

Since AsyncTask() method is deprecated, I am trying to replace it. Previously AsyncTask() was used to load CardViews into a RecyclerView list from a Room database. I am trying to use CompletableFuture() as a replacement but the list does not load. The Dao method for "List getAllCards()" is giving an error message in Android Studio "Return value of the method is never used" so it sounds like the list is never obtained from the the database. The Repository gets the List method from the ViewModel and the ViewModel gets the List method call in the MainActivity.

I also want to avoid "ExecutorService.submit(() - > cardDao()).get()" to load the list, since it is blocking. I show below the ExecutorService submit(() method that was working fine, for reference.

What am I missing here since the list is not loading?

Repository

public List<Card> getAllCards() {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

        CompletableFuture.supplyAsync(() -> {
            List<Card> loadAllCards = new ArrayList<>();
            cardDao.getAllCards();
            return loadAllCards;
        }).thenAcceptAsync(loadAllCards -> getAllCards());
    }
    return null;
}

Dao

@Dao
public interface QuickcardDao {

    @Query("SELECT * FROM cards ORDER BY Sortorder DESC")
    List<Card> getAllCards();
} 

Here is the AsyncTask() in the Repository that I am trying to replace:

public CardRepository(Application application) {
    CardRoomDatabase db = CardRoomDatabase.getDatabase(application);
    cardDao = db.cardDao();
}

public List<Card> getAllCards() {
    try {
        return new AllCardsAsyncTask(cardDao).execute().get();
    } catch (ExecutionException | InterruptedException e) {
        e.printStackTrace();
    }
    return null;
}

// AsyncTask for reading an existing CardViews from the Room database.
private static class AllCardsAsyncTask extends AsyncTask<Void, Void, List<Card>> {

    private CardDao cardDao;

    AllCardsAsyncTask(CardDao dao) {
        cardDao = dao;
    }

    @Override
    public List<Card> doInBackground(Void... voids) {

        return cardDao.getAllCards();
    }
}

Here is the submit(() method in the Repository that I am trying to replace:

public List<Card> getAllCards() {

    List<Card> newAllCards = null;
    try {
        newAllCards = CardRoomDatabase.databaseExecutor.submit(() -> cardDao.getAllCards()).get();
    }
    catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }
    return newAllCards;
}

// End



from android: load List from Room using CompletableFuture?

No comments:

Post a Comment