0

I have a ListView to display a list of data, which I need to get from a DB first - the loading happens in an AsyncTask.
Now I want to refresh my list as soon as the AsyncTask has finished loading - I am using this to call adapter.notifyDataSetChanged(); in my Activity, but the List doesnt refresh.
Full Code:
In OnCreate:

adapter = new SimpleAdapter(ShopSwitchActivity.this, listData,
                android.R.layout.simple_list_item_2,
                new String[] {"name", "address"},
                new int[] {android.R.id.text1,
                           android.R.id.text2});

        listView.setAdapter(adapter);


        AsyncTask<String, Void, List<Map<String,String>>> task = new LoadList(ShopSwitchActivity.this).execute();
        try {
            listData = task.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

After Task is completed:

@Override public void onTaskCompleted() { adapter.notifyDataSetChanged(); }

listData = task.get(); returns the expected Result, it´s just not shown in the List. (There is no crash or anything and every line gets called)
What am I missing here?

EDIT: Working Code:

@Override
    public void onTaskCompleted() {
        adapter = new SimpleAdapter(ShopSwitchActivity.this, listData,
                android.R.layout.simple_list_item_2,
                new String[] {"name", "address"},
                new int[] {android.R.id.text1,
                           android.R.id.text2});

        listView.setAdapter(adapter);
    }

instead of just
@Override public void onTaskCompleted() { adapter.notifyDataSetChanged(); }

Community
  • 1
  • 1
Benjamin Schwalb
  • 1,124
  • 11
  • 31
  • Try calling `adapter.notifyDataSetChanged();` after you call `listData = task.get();` – Ken Wolf Jul 09 '13 at 07:20
  • It IS called after `listData = task.get();` (after _task_ is completed) – Benjamin Schwalb Jul 09 '13 at 07:22
  • I meant directly after that line in your `try` block, but OK, I'm not familiar with `onTaskCompleted()`. – Ken Wolf Jul 09 '13 at 07:24
  • I have two remarks . 1.Why dont you call the adapter.notifyDataSetChanged() method directly in the onPostExecute() method 2. Probably the adapter.notifyDataSetChanged() methhod does not get called in UI thread. – Rohit Walavalkar Jul 09 '13 at 07:28

1 Answers1

2

You need recreate Adapter and setAdapter every time you want to refresh data, or extend SimpleAdapter, because SimpleAdapter constructor clone listData and use its own and it hasn't any methods to renew data.

And don't forget, Java can't pass arguments by reference.

neworld
  • 7,757
  • 3
  • 39
  • 61