就我而言,我使用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()方法创建一个单独的类?预先感谢!
SOLUTION
根据Priyankagb的建议,我开始使用runOnUiThread():
if (dao.findByNumber(1).isOpen) {
runOnUiThread(() -> button.setBackgroundResource(R.drawable.active_button_shape));
}
不,这不是线程安全的。您必须使用onPostExecute()
或也可以使用runOnUiThread()
将按钮背景更改为直接execute()
喜欢...
runOnUiThread(new Runnable() {
@Override
public void run() {
button.setBackgroundResource(R.drawable.active_button_shape)
}
});