How can I load more data into a ListView on Android when the end of the list is reached?

0

Good, in my project I need to upload a news section in my ListView , obviously I can already list them, the problem is that as I have many news what I want is to load them in parts, that is suppose I have 3000 news, What I want is to load 500 news first, when the user finishes watching the news, obviously he would have to swipe down to be able to load the next 500.

I would like to know the method of swiping down to upload new news (obviously without losing the previous news since I am using the view holders), I hope you let me understand. Regards, programmer friends.

    
asked by Manuel Ces 15.02.2017 в 18:42
source

1 answer

2

If I understand you, you want to load a part of the entire list and continue loading more blocks when the user reaches the end of the list. For that you can use a OnScrollListener . First you define your OnScrolllistener as the inner class of the ListView :

class MiOnScrollListener implements OnScrollListener{
    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
        // comprobar si llegemos al fin de la lista
        distanciaDeFin = totalItemCount - firstVisibleItem - visibleItemCount;
        // si la distancia hasta el fin de datos ya cargados es menor a 5, cargamos más
        // la distancia para cargar puedes adaptar parra llegar al "feel" que quieres
        if (distanciaDeFin < 5) cargaProximoBloque(totalItemCount);

}

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {}
} 

In your ListView you have to do two things:

  • place the listener in onCreate
  • implement cargaProximoBloque

in onCreate :

setOnScrollListener(new MiOnScrollListener());

and the implementation of cargarProximoBloque

void cargarProximoBloque(int totalItemCount){
    // tu código para buscar el bloque desde totalItemCount +1
    // y assumiendo que usas un ArrayAdapter construido con una lista:
    adapter.addAll((Collection) proximoBloque);
}

I hope that it reaches you to complete your activity. Any questions do not hesitate to ask.

A tip: Use a ArrayAdapter , but make sure you build it with a list as a parameter ( ArrayList for example) in the constructor. There are dragons in this class. If you build it with a simple fix, the adapter does not allow you to add more data later.

    
answered by 15.02.2017 в 19:17