gpt4 book ai didi

java - AsyncTask.execute() 并更改 UI

转载 作者:行者123 更新时间:2023-12-01 19:29:09 25 4
gpt4 key购买 nike

在我的例子中,我使用 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
}
});

这是一个线程安全的解决方案吗?或者需要创建一个单独的类,并重写 onPostExecute() 方法来更改 UI?提前致谢!

解决方案

根据 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)
}
});

关于java - AsyncTask.execute() 并更改 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60334394/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com