input
input

Reputation: 7519

Android: Repository function returns false using Room

I've added a favourites button to the recyclerview item and using Room to save the favourite data. What's happening is that the Repository function isFavourites returns false even if the data exists in the database.

Since Room isn't supposed to run on the main thread, I'm using Executors and while logging, I realised that the boolean variable inside the Executors method returns true but outside, it returns false.

How do I fix this?

FavouriteDAO.java

@Dao
public interface FavouriteDao {

    @Query("SELECT EXISTS (SELECT 1 FROM favourites WHERE id=:id)")
    public boolean isFavourite(int id); 

}

FavouriteRepository.java

boolean isFavourite(int id) {
            final boolean[] b = new boolean[1];
            Executors.newSingleThreadExecutor().execute(() -> {
                b[0] = favouriteDao.isFavourite(id);
                Log.d(TAG, "Favourite is" + b[0]); <--- returns true if data exists
            });
            Log.d(TAG, "Favourite is" + b[0]); <--- returns false always
            return b[0];
        }

FavouriteViewModel.java

 public boolean isFavourite(int id) {   return mRepository.isFavourite(id); }

This always returns false in Activity:

  boolean isFavourite = favouriteViewModel.isFavourite(id);

Upvotes: 0

Views: 484

Answers (1)

Gavin Wright
Gavin Wright

Reputation: 3212

You're checking the value of your boolean before the asynchronous task completes, so you're always reading its default value of false. You need some sort of callback for when the Executor task completes:

Java executors: how to be notified, without blocking, when a task completes?

You could also use RXJava, which has built-in solutions for this.

Upvotes: 2

Related Questions