Refresh data in a custom Android Adapter

An Adapter is an object that provides data to certain components like a ListView object or a Spinner object. There are distinct classes that implement the Adapter class, such as ArrayAdapter, which loads an array of objects. We can create a custom adapter that extends the ArrayAdapter class to create custom items.
Let’s say that we want to display Event objects in a ListView. This is our custom adapter:

public class MyCustomAdapter extends ArrayAdapter<MyEvent> {
    private final Context context;
    private List<MyEvent> events;

    public MyCustomAdapter(Context context, int layoutResourceId, List<MyEvent> events) {
        super(context, layoutResourceId, data);
        this.context = context;
        this.events = events;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Custom view
    }
}

In the constructor method, the adapter saves the list of objects that will be displayed in the view. If we want to refresh/change this data after creating the adapter, add a new method to the adapter:

public void refreshEvents(List<MyEvent> events) {
    this.events.clear();
    this.events.addAll(events);
    notifyDataSetChanged();
}

This refresh method clears all the data from the list and updates it with new data. Alternatively you can create different methods to add or remove items. In any case, the most important part is to invoke the notifyDataSetChanged method. The notifyDataSetChanged method notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.

Finally, from the activity or fragment that contains the list, invoke the previous method with the new data:

mAdapter.refreshEvents(newListOfEvents);

Consider the case in which the refresh method is not called from the UI thread. For example, if the data is updated after a server request:

getActivity().runOnUiThread(new Runnable() {
    @Override
    public void run() {
        mAdapter.refreshEvents(newListOfEvents);
});
Share Button

6 Comments

  1. Hola Belén… has manejado imágenes dentro de la información que forma parte del adaptador y finalmente es la que se muestra al usuario?… Te pregunto porque he estado realizando un par de aplicaciones y me he topado con el problema de que al hacer el scroll al listview donde muestro la información la cual incluye una imagen (logo de empresa…), estas se van desfasando. el adaptador lo he realizado de manera manual como se explica en diversos tutoriales, y también he utilizado la biblioteca picasa. Agradezco lo que me puedas compartir a la experiencia que tienes. En algún momento te envié invitación por hangouts ¿Te puedo contactar por dicho medio, para en tu tiempo libre poder compartir temas de desarrollo de apps y finalmente conocerte?. Saludos

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload the CAPTCHA.