MDodd423
MDodd423

Reputation: 23

How to query Room database for LiveData<String> while passing a variable

When I hard code the variable the query works:

From the Dao:

@Query("SELECT amount FROM note_table WHERE item = 'Apple'")
    LiveData<String> getAmount();

but when I try to pass a variable it doesn't.

 @Query("SELECT amount FROM note_table WHERE item = :items")
    LiveData<String> getAmountwithItem(String items);

From the ViewModel:

private final LiveData<String> NoteAmount, NoteAmountwithItem;

NoteAmount = repository.getAmount();
NoteAmountwithItem = repository.getNoteAmountwithItem();

 LiveData<String> getAmount() {
        return NoteAmount;
    }

 LiveData<String> getNoteAmountwithItem() {
        return NoteAmountwithItem;
    }

From the Repository:

private final LiveData<String> NoteAmount, NoteAmountwithItem;

NoteAmount = noteDao.getAmount();
NoteAmountwithItem = noteDao.getAmountwithItem();

LiveData<String> getAmount() {
        return NoteAmount;
    }

LiveData<String> getNoteAmountwithItem() {
        return NoteAmountwithItem;
    }

From MainActivity.java

noteViewModel.getAmount().observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String queryAmount) {
                if(queryAmount != null){
                    updateamount = String.valueOf(Integer.parseInt(queryAmount) + 1);
                    testTextView.setText("Amount: " + updateamount);
                }else{
                    updateamount = "1";
                }
            }
        });

This gives me the amount of Apples in queryAmount but I have different fruits and want to pass the fruit as a variable and get the amount of specific fruits.

Upvotes: 0

Views: 178

Answers (1)

Zain
Zain

Reputation: 40888

You need to pass a String argument to getAmountwithItem() from activity all the way down to the DAO interface

In Dao (Keep it the same as yours):

@Query("SELECT amount FROM note_table WHERE item = :items")
LiveData<String> getAmountwithItem(String items);

In Repository:

LiveData<String> getNoteAmountwithItem(String item) {
    return noteDao.getAmountwithItem(item);
}

In ViewModel:

LiveData<String> getNoteAmountwithItem(String item) {
    return repository.getNoteAmountwithItem(item);
}

In Activity (pass the String you want to look for):

noteViewModel.getNoteAmountwithItem("Apple").observe(this, new Observer<String>() {
    @Override
    public void onChanged(@Nullable String queryAmount) {
        if(queryAmount != null){
            updateamount = String.valueOf(Integer.parseInt(queryAmount) + 1);
            testTextView.setText("Amount: " + updateamount);
        }else{
            updateamount = "1";
        }
    }
});

Upvotes: 2

Related Questions