【发布时间】:2012-07-13 12:30:25
【问题描述】:
我有一个活动,其中一个列表视图显示项目。这个活动有三个按钮和一个带有多个其他按钮的菜单。
当我按下一个按钮时,会启动一个新线程,从 Web 服务获取数据,填充列表视图。然后显示列表视图。
唯一的问题是每次我按下一个按钮时,我都会启动一个线程。根据检索数据所需的时间,有时会发生列表视图未填充好的数据(用户不等待一个线程完成并按下另一个按钮)
首先我尝试取消线程,但它不起作用(异步任务或使用 thread.interrupt)
我怎样才能停止以前的线程,以便列表视图将被最后的数据填充?
感谢您的帮助:)
// Items to be displayed in the listview
private ArrayList<HashMap<String, Object>> oItems = new ArrayList<HashMap<String, Object>>();
// Launch the thread when toggle is checked
button.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
LoadListView();
}
}
});
oMenu.setOnChildClickListener(new OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
LoadListView();
return true;
}
});
private void LoadListView() {
new Thread(ListViewRunnable).start();
}
private Runnable ListViewRunnable = new Runnable() {
public void run() {
while (GetItems() < 1) {
}
MainHandler.post(new Runnable() {
public void run() {
}
});
}
private int GetItems() {
try {
HashMap<String, Object> oItem;
//Get items from web services
List<ItemFromService> oItemsFromService = GetItemsFromWebService();
for (oItemFromService : oItemsFromService) {
oItem = new HashMap<String, Object>();
oItem.put("ID", oItemFromService.get_iID());
oItem.put("Label", oItemFromService.get_sLabel());
oItems.add(oItem);
}
MainHandler.sendEmptyMessage(GOT_ITEMS);
} catch (Exception e) {
}
return 1;
}
}
private Handler MainHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == GOT_ITEMS) {
adapter.notifyDataSetChanged();
}
}
};
【问题讨论】:
-
您是否使用 Thread 或 AsyncTask 或其他工具来生成线程?一些示例代码可能会有所帮助。
-
列出您正在使用的一些代码,以便于理解。
-
我正在使用可运行的线程。我的线程连接到 Web 服务,用对象填充数组,然后调用 .notifyDataSetChanged() 方法来刷新列表视图。
标签: android multithreading listview android-activity