对于我来说,我使用AsyncTask.execute()方法连接到Room数据库并更改UI元素:
AsyncTask.execute(() -> {
Database db = Room.databaseBuilder(this.getApplicationContext(),
Database.class, "name-database").build();
Dao dao = db.getDao();
if (dao.findByNumber(1).isOpen) { // get data from the database
button.setBackgroundResource(R.drawable.active_button_shape) // change UI-element
}
});
这是线程安全的解决方案吗?还是需要为更改UI创建一个具有覆盖的onPostExecute()方法的单独类?预先感谢!
解决方案
根据Priyankagb的建议,我开始使用runOnUiThread():
if (dao.findByNumber(1).isOpen) {
runOnUiThread(() -> button.setBackgroundResource(R.drawable.active_button_shape));
}
答案 0 :(得分:3)
否,这不是线程安全的。您必须使用onPostExecute()
,也可以使用runOnUiThread()
将按钮背景更改为直接的execute()
喜欢...
runOnUiThread(new Runnable() {
@Override
public void run() {
button.setBackgroundResource(R.drawable.active_button_shape)
}
});