将新数据发送到服务器后刷新ListView

时间:2013-09-06 10:00:26

标签: android android-listview

我有一个显示ListView的活动。我使用AsyncTask从服务器获取数据并将其填充到列表中。

当我点击操作栏时,会启动一个新的活动(样式为对话框) - 用户添加一些数据点击“发送”并将其发送到服务器。然后,当我想刷新列表并添加新数据时,此对话框活动将关闭并返回上一个。

尝试在onResume()方法上运行AsyncTask,但是当我得到新数据和之前的数据时,我得到它们两次,因为AsyncTask也在onCreate()上运行。

1)即使第一次活动通过onStart, onCreate and onResume,我也会将列表数据显示两次。 我应该使用像旗子这样的东西,所以第一次活动开始时不应该运行那段代码吗?

2)我无法想象notifyDataSetChanged如何帮助我,因为我从服务器填充数据。我有一个自定义适配器扩展ArrayAdapter

代码

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);


    JSONSpotTask task = new JSONSpotTask();     //task
    task.execute();
    try {
        task.get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }

    list1 = (ListView) findViewById(R.id.listview1);
    ta = new TipsAdapter(this, R.layout.row_list_item, results);
    list1.setAdapter(ta);


}   



@Override
protected void onResume() {                     
    super.onResume();                               

    JSONSpotTask task = new JSONSpotTask();     //task
    task.execute();
    try {
        task.get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }

    list1 = (ListView) findViewById(R.id.listview1);
    ta = new TipsAdapter(this, R.layout.row_list_item, results);
    list1.setAdapter(ta);
}

谢谢

1 个答案:

答案 0 :(得分:0)

只有在更新结果数组时才应使用notifdatasetchanges。否则,您应该在onPostExecute回调中创建带有结果数组的新适配器并将其绑定到listview

相关问题