Search code examples
androidintegerandroid-room

Obtaining integer from room query math result


I'm trying to obtain the result of a subtraction between two rows in the database. Users specify the conditions on spinners (populated with the "model" column), press a button and the query is launched.

Spinners are properly saving the position into sharedpreferences and later obtaining it.

Button function:

public int value;

//later on
TextView converter = findViewById(R.id.converter);
        AppExecutors.getInstance().diskIO().execute(() -> {
    LiveData<Integer> value = mDb.personDao().loaddifferconstants(spinA, spinB);
    converter.setText(""+value); //quick dirty method
});

Dao

@Query("SELECT t1.const - t2.const AS result FROM person t1 JOIN person t2 WHERE t1.model == :spinA AND t2.model == :spinB")
LiveData<Integer> loaddifferconstants(String spinA , String spinB);

The query does work in DBBrowser, as a direct sql query. So I guess the error lies on how the result is processed into an integer. I tried listing the result, using both livedata integer, int, list... trying to pass it as a String... Failed.

Update 1: Integer doesn't work either. Actually Integer count doesn't work either, with the Dao being

@Query("SELECT COUNT(*) FROM PERSON")
    int count();

Thank you


Solution

  •     LiveData<Integer> value = mDb.personDao().loaddifferconstants(spinA, spinB);
        converter.setText(""+value); //quick dirty method
    

    value is a LiveData. This will cause the query to be executed asynchronously. By the next statement, that query will not have completed, and the LiveData will not have the query result.

    Either:

    • Remove LiveData from loaddifferconstants() and have it simply return Integer, so the query will be executed synchronously, or
    • Consume the LiveData properly, by registering an observer

    Since you seem to by trying to call those two lines inside your own background thread, I recommend the first approach: get rid of the LiveData. That would give you:

    @Query("SELECT t1.const - t2.const AS result FROM person t1 JOIN person t2 WHERE t1.model == :spinA AND t2.model == :spinB")
    Integer loaddifferconstants(String spinA , String spinB);