从另一个线程调用adapter.notifyDataSetChanged() [英] Call adapter.notifyDataSetChanged() from another thread
问题描述
我想从另一个线程调用adapter.notifyDataSetChanged()
.我读到我应该使用AsyncTask
并在执行后执行adapter.notifyDataSetChanged()
.
I want to call adapter.notifyDataSetChanged()
from another thread. I read that I should use an AsyncTask
and do the adapter.notifyDataSetChanged()
in post execute.
我只能在当前活动(可能是父活动或子活动)上每5秒执行一次AsyncTask
,因为只有一个活动可以同时执行asynctask.
I must execute the AsyncTask
every 5 seconds only on the current activity (might be parent or child activity) because only one activity can do the asynctask at the same time.
我应该创建一个TimerTask
来每5秒执行一次AsyncTask
,在我开始另一个活动时将其停止并在onResume
中重新启动它吗?
Should I create a TimerTask
which executes the AsyncTask
every 5 seconds, stop it when I start another activity and start it back in onResume
?
这是我的线程代码,用于更新当前活动的ListView
.
Here is my code for the thread which updates the ListView
of the current Activity.
private void runEventHandler() {
new Thread() {
public void run() {
while (true) {
try {
runOnUiThread(new Runnable() {
@Override
public void run() {
users.add(new User(10, "a", false));
adapter.notifyDataSetChanged();
}
});
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
现在,当添加新用户时,我必须能够更新子活动的ListViews
.
Now I must be able to update the child activities' ListViews
when a new User is added.
推荐答案
一种可能的方法是,在两个活动中都创建一个标志来控制线程的运行(以下代码不是可运行的,只是示例,以了解您可以执行的操作)做):
one possible way is that you create a flag in both activity to control your threads to be run ( the following codes are not runable just example to understand what you can do):
Activity A
{
public static boolean stopThread = false;
@Override
public void onResume()
{
super.onResume();
// put your code here...
stopThread =false;
runEventHandler();
}
private void runEventHandler() {
new Thread() {
public void run() {
while (A.stopThread != false) {
try {
runOnUiThread(new Runnable() {
@Override
public void run() {
users.add(new User(10, "a", false));
adapter.notifyDataSetChanged();
}
});
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
@Override
protected void onStop(){
super.onStop();
stopThread =true;
}
}
Activity B
{
public static boolean stopThread = false;
@Override
public void onResume()
{
super.onResume();
// put your code here...
stopThread =false;
runEventHandler();
}
private void runEventHandler() {
new Thread() {
public void run() {
while (B.stopThread != false) {
try {
runOnUiThread(new Runnable() {
@Override
public void run() {
users.add(new User(10, "a", false));
adapter.notifyDataSetChanged();
}
});
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
@Override
protected void onStop(){
super.onStop();
stopThread =true;
}
}
也可以使用onPause()
代替onStop()
.取决于您的程序概念.
also you can use onPause()
instead of onStop()
. depends on your program concept.
这篇关于从另一个线程调用adapter.notifyDataSetChanged()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!