RefreshListView icon indicating copy to clipboard operation
RefreshListView copied to clipboard

Call the listener on a background thread

Open JoanZapata opened this issue 12 years ago • 1 comments

Updating a list is almost always something that includes IO. That's why you start a new AsyncTask in you sample code:

  @Override
  public void onCreate(Bundle savedInstanceState) {
    [...]
    // Add callback to RefreshListView
    list.setRefreshListener(new OnRefreshListener() {

      @Override
      public void onRefresh(RefreshListView listView) {
        // Task to do while refreshing
        new BackgroundTask().execute();

      }
    });
    [...]
  }
 [...]

  // Background AsyncTask
  private class BackgroundTask extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {
      [...] // Do background task

      return string;
    }

    @Override
    protected void onPostExecute(String newApi) {
      [...] // Update adapter

      // call on RefreshListView to hide header and notify the listview, refreshing is done
      list.finishRefreshing();
    }
  }

Code could be much shorter if you were calling onRefresh() already in a background thread.

@Override
  public void onCreate(Bundle savedInstanceState) {
    [...]
    // Add callback to RefreshListView
    list.setAsyncRefreshListener(new OnRefreshListener() {
      @Override
      public boolean onAsyncRefresh(RefreshListView listView) {
          // Do background task and add data to the adapter
          // return true if notifyDataSetChanged() needs to be called in UI thread, false otherwise.
      }
    });
    [...]
  }

list.finishRefreshing(); would then be implicitly called after onRefresh returns.

JoanZapata avatar Jun 08 '13 09:06 JoanZapata

That's a great idea, this way the only thing to do for developers is to implement the listener. Nothing more. I'll try to work on this ASAP.

jeremiemartinez avatar Jun 08 '13 10:06 jeremiemartinez