我有一个从服务器加载的列表。以下是执行此操作的任务:
class LoadActivities extends AsyncTask <String, String, String> {
protected String doInBackground(String ... args) {
final RestAdapter restAdapter = new RestAdapter.Builder().setServer("http://10.0.2.2:8080").build();
final MyService apiManager = restAdapter.create(MyService.class);
final Activity activity = apiManager.getActivity("some user", act_id);
//tasks in activity
for (Tasks t : activity.getTasks()) {
String r_id = t.getId()+"";
String name = t.getName();
HashMap<String, String> map = new HashMap<String, String>();
map.put("activity_id", act_id);
map.put("t_id", t_id);
map.put("t_name", name);
tasksList.add(map);
}
return null;
}
protected void onPostExecute(String file_url) {
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
TaskActivity.this, tasksList,
R.layout.list_item_rec, new String[] { "act_id", "t_id", "t_name"}, new int[] {
R.id.act_id, R.id.task_id,R.id.task_name });
setListAdapter(adapter);
}
});
}
}
所有这一切都很好。但是,在另一个屏幕上,我在服务器上添加了一个项目,然后我回到这个屏幕再次显示列表。在回来时我想刷新列表,以便它反映新添加的项目。
问题
我应该刷新整个列表吗?我已经尝试过再次调用上面的类。像这样:
public boolean onOptionsItemSelected(MenuItem menuItem) {
if (menuItem.getTitle().toString().equalsIgnoreCase("save")) {
new CreateTask(this,activityName.getText().toString(), actId).execute();
Intent returnIntent = new Intent();
setResult(RESULT_OK, returnIntent);
finish();
return true;
}
return true;
}
...回到这个屏幕上
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
Log.d("This is result", result);
new LoadActivities().execute();
}
}
}
问题在于它正在重新填充列表。意思是我每个活动都有重复。我该如何解决这个问题?
OR 有没有办法让我不必重新加载整个列表,而只是添加一个项目到现有列表?
答案 0 :(得分:0)
首先,在方法“onPostExecute”中,您不需要调用“runOnUiThread”,因为“onPostExecute”是在UI线程中运行的。
其次,如果要在页面前刷新ListView,可以在首页使用“onActivityResult”,但如果服务器数据已更新,只需再次从服务器获取数据并更新数据集(列表) ),然后调用adapter.notifyDataSetChanged()。
希望能帮到你!
答案 1 :(得分:0)
你应该让我们和ArrayAdapter
让它处理清单。
立即创建并设置ArrayAdapter,然后根据需要添加项目。您必须覆盖适配器中的getView
,但对于一个不是复杂代码的简单视图。
一般结构如下:
onCreate(...) {
// It's okay if the adapter is empty when you attach it to the ListView
setListAdapter(new ArrayAdapter<ListItemType>(...));
}
onPostExecute(...) {
// Once you've retrieved the list of items from the server, add them to
// the adapter
ArrayAdapter adapter = (ArrayAdapter) getListAdapter();
adapter.add([items retrieved from server]);
}
onActivityResult(..., Intent data) {
// Add the newly added item, either pass it back directly, or get the new
// list from the server and compare to see which item needs adding.
// For simplicity, we'll assume it was passed back by the activity
ListItemType newlyAddedItem = (ListItemType) data.getParcelableExtra("key");
ArrayAdapter adapter = (ArrayAdapter) getListAdapter();
adapter.add(newlyAddedItem);
}