【发布时间】:2020-11-21 22:22:11
【问题描述】:
我使用 ScheduledExecutorService 每 15 秒从网站获取数据:
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
scheduler.scheduleAtFixedRate(this::refresh, 0, 15, TimeUnit.SECONDS);
这是每 15 秒调用一次的方法:
public void refresh() {
Site.refreshData();
System.out.println("Refreshed Data");
LinearLayout listView = findViewById(R.id.linearLayout);
System.out.println("Size: " + List.getList().size());
for (int i = 0; i < List.getList().size(); i++) {
Entry entry = List.getList().get(i);
CardView cardView = (CardView) LayoutInflater.from(
getApplicationContext()).inflate(R.layout.card, listView, false);
ImageView checkedView = (ImageView) cardView.getChildAt(0);
checkedView.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),
entry.isChecked() ? R.drawable.check : R.drawable.cross));
TextView name = (TextView) cardView.getChildAt(1);
name.setText(entry.getName());
TextView comment = (TextView) cardView.getChildAt(2);
comment.setText(entry.getComment());
listView.addView(cardView, i);
}
System.out.println("Added Cardviews");
listView.invalidate();
System.out.println("Refreshed LinearLayout");
}
我添加了多个打印,作为一个穷人调试器,我只到达打印 ArrayList 大小的地步。从那里开始没有任何东西被打印出来,就像执行停止一样。
我确定错误发生在 for 循环内。我通过添加打印进行了检查,它显示了当前的i,它刚刚停止在 4,即使列表大小为 57。
有什么问题?
【问题讨论】:
-
您的问题是您在工作线程中添加了 GUI 元素。引用 Android 文档:因此,您不得从工作线程操作您的 UI — 您必须从 UI 线程对您的用户界面进行所有操作。
-
@Robert 我怎么能做到这一点?我必须使用 ScheduledExecutorService 刷新我的数据,那么我将如何“返回”到主线程来操作 UI?由于 SES 调用的方法和内部的所有内容都将在 SES-Thread 而不是主线程中运行。请对此提供一些详细的答案。
-
常见的做法是在工作线程上更新一个数据结构,然后让主线程做更新工作:stackoverflow.com/questions/16483462/…
标签: java android android-cardview android-scrollview scheduledexecutorservice