首先,使用postdelayed()不会重复运行您的代码。如果您想以重复模式运行代码,请使用以下代码。这将在每5秒后运行。
ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run()
{
runOnUiThread(new Runnable(){
@Override
public void run() {
new GetContacts().execute();
}
});
}
}, 0, 5, TimeUnit.SECONDS);
您正在遵循的代码在postExecute()中每次创建SimpleAdapter的新实例,因此您将一遍又一遍地看到相同的数据。因此,如果要更新适配器,请将SimpleAdapter实例作为类成员创建,并将postExecute()替换为此内容。
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
if(adapter == null)
{
adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[] { TAG_NAME, TAG_EMAIL,
TAG_PHONE_MOBILE }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
else
{
adapter.notifyDataSetChanged();
}
}
现在这会更新适配器,但会添加相同的联系人。
`public synchronized void refreshAdapter(List itemList) {
this.itemList = itemList;
notifyDataSetChanged();
}`
- Jeremy W