我正在努力实现以下目标:
我在达到上述第5点时遇到了问题。这就是我到目前为止所做的:
我有一个AyncTask
如下:
public class MyActivity extends SherlockListActivity {
ArrayList<HashMap<String, String>> taskList;
//this grabs data from server and loads it in ArrayList
protected void loadList() {
taskList = new ArrayList<HashMap<String, String>>();
final RestAdapter restAdapter = new RestAdapter.Builder().setServer("http://10.0.2.2:8080").build();
final TaskService apiManager = restAdapter.create(TaskService.class);
final Task task = apiManager.getTask("someuser", task_id);
for (Item item : task.getItems()) {
String t_id = t.getId()+"";
String name = t.getName();
HashMap<String, String> map = new HashMap<String, String>();
map.put("act_id", act_id);
map.put("t_id", t_id);
map.put("t_name", name);
taskList.add(map);
}
}
public void onCreate (Bundle b) {
new LoadItems().execute();
}
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getTitle().equals("Create")) {
Intent create = new Intent(getApplicationContext(), CreateTask.class);
startActivityForResult(create, 1);
return true;
}
return true;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
//item got added now load again from server
if (resultCode == RESULT_OK) {
String result = data.getStringExtra("result");
new UpdateItems.execute();
adapter.notifyDataSetChanged();
}
}
}
class UpdateItems extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
loadList();
return null;
}
}
class LoadItems extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
loadList();
}
protected void onPostExecute(String file_url) {
adapter = new SimpleAdapter(
MyActivity.class, taskList,
R.layout.list_item_rec, new String[] { "act_id", "t_id", "t_name"}, new int[] {
R.id.act_id, R.id.t_id,R.id.t_name });
setListAdapter(adapter);
}
}
问题
如何在onActivityResult
中重新加载来自服务器的数据。基于以上所述,我正在做的是创建另一个AynchTask,仅用于再次加载数据然后调用notifyDataSetChanged()
。这似乎不起作用。
我的流程错了吗?有一个更好的方法吗?我很难过......
答案 0 :(得分:1)
您必须使用UpdateItems
onPostExecute()
方法重新加载数据。因为您要在AsynchTask
中加载数据,它会在另一个线程中加载数据并更新ListView
但是当时没有加载列表..所以改变你的AsynchTask
就像这样......
class UpdateItems extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
loadList();
return null;
}
@Override
protected void onPostExecute(String result) {
adapter.notifyDataSetChanged();
}
}
并在adapter.notifyDataSetChanged()
onActivityResult()