简体   繁体   English

从房间查询数学结果中获取 integer

[英]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. Spinners 正确地将 position 保存到 sharedpreferences 中并稍后获取它。

Button function:按钮 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.该查询在 DBBrowser 中确实有效,作为直接 sql 查询。 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.所以我猜错误在于如何将结果处理成 integer。我尝试列出结果,同时使用 livedata integer,int,list ...试图将其作为字符串传递...失败。

Update 1: Integer doesn't work either.更新 1: Integer 也不起作用。 Actually Integer count doesn't work either, with the Dao being实际上 Integer 计数也不起作用,道是

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

Thank you谢谢

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

value is a LiveData . value是一个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.到下一条语句时,该查询还没有完成, LiveData将没有查询结果。

Either:任何一个:

  • Remove LiveData from loaddifferconstants() and have it simply return Integer , so the query will be executed synchronously, orloaddifferconstants()中删除LiveData并让它简单地返回Integer ,这样查询将同步执行,或者
  • Consume the LiveData properly, by registering an observer通过注册观察者来正确使用LiveData

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 .由于您似乎试图在自己的后台线程中调用这两行,因此我推荐第一种方法:摆脱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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM