Endless Scrolling Listview Not Working

Endless scrolling listview not working

To Show only 10 item first time in ListView and show more items on scroll follow following steps:

STEP 1: Create a chunkList method which divide ArrayList in parts of size 10:

static <T> List<ArrayList<T>> chunkList(List<T> list, final int L) {
List<ArrayList<T>> parts = new ArrayList<ArrayList<T>>();
final int N = list.size();
for (int i = 0; i < N; i += L) {
parts.add(new ArrayList<T>(
list.subList(i, Math.min(N, i + L)))
);
}
return parts;
}

STEP 2: Create ArrayList and a counter which show current part :

    private boolean isLoadingMore=false;
Handler mHandler = new Handler();
List<ArrayList<HashMap<String,String>>> mainArrayList;
private int count=0;

STEP 3: In onPostExecute break result and show data in ListView:

protected void onPostExecute(ArrayList<HashMap<String,String>> result) {

super.onPostExecute(result);
// your code here...
mainArrayList=chunkList(result,10);
isLoadingMore=false;
count=0;
adapter = new CustomAdapterSent(Interestsent.this,
mainArrayList.get(count));
setListAdapter(adapter);
}

}

STEP 4: Create addAll method in Adapter to append data in current data source :

public void addAll(ArrayList<HashMap<String,String>> moreData){
this.listData.addAll(moreData);
this.notifyDataSetChanged();
}

STEP 5: In onLoadMore load more data in ListView:

mHandler = new Handler();
listview.setOnScrollListener(new EndlessScrollListener() {
@Override
public void onLoadMore(int page, int totalItemsCount) {
if(count<mainArrayList.size()-1)
{
if(adapter !=null){
count++;
if(!isLoadingMore){
isLoadingMore=true;
mHandler.postDelayed(loadMoreRunnable,1000);
}
}
}
}
});
}

Runnable loadMoreRunnable = new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
if(count<mainArrayList.size())
{
if(adapter !=null){
count++;
adapter.addAll(mainArrayList.get(count));
mHandler.removeCallbacks(loadMoreRunnable);
isLoadingMore=false;
}
}
}
};

How to implement endless scrolling listview

you didn't use EndlessListView in your Fragment. As I looked your response, it includes pagination. So, you need to request with page number to use endless scroll.

This is just flow for Endless Listview. If your code still doesn't work, I hope you can learn sample projects after read this messages. I added only parts you need. Thanks

Endless scroll only shows limited data on listview. When user scroll down to bottom, it will get next limited data from server. So you need to add current_page paramater in your request. I don't know exactly your api.

First, you need variable for current_page which initialize with 0

You have to know when to stop. You response has total_page field for that. Save and add validation

Then you need to know when to request next page. For that,you already have codes in onScroll within EndlessListView. That code calculate and tell when user scroll down to bottom and it called

listener.loadData();

to request new data. But you still need to add listener for that. You already have

public void setListener(EndLessListener listener) {
this.listener = listener;
}

You need to create Interface with the name EndlessListener and implements in your fragment. EndlessListener Interface will include loadData() function that request to server. After that you need to add listener for the listview.

endlessListView.setListener(this);

Endless scrolling ListView

First, get rid of the EndlessScrollListener. Then, update your AsyncTask to fetch the data, append it to the already-in-use adapter, and notify the adapter of the data set change. Finally, in your adapter, add a check for if you reach the end of the list and request the next page. I should warn you, however, that you'll want to keep track of your async task and prevent it from being recreated if you scroll the last view into place while it's already loading.

AsyncTask

class RecentTracksTask extends AsyncTask<Integer, Void, Void> {

ArrayList<Track> recentTracks;

@Override
protected Void doInBackground(Integer... page) {
try {
// Get a page of 15 tracks
// Simplified - getPage accepts 'page' and 'limit' parameters and returns a Collection<Track>
recentTracks = new ArrayList<Track>(getPage(page[0], 15));

} catch () {}

return null;
}

@Override
protected void onPostExecute(Void result) {
ListView listView = (ListView) getActivity().findViewById(R.id.listview);
ArrayAdapter adapter = (ArrayAdapter) listView.getAdapter();
if(adapter == null) {
adapter = new TracksAdapter(getActivity(), recentTracks);
listView.setAdapter(adapter);
} else {
adapter.addAll(recentTracks);
adapter.notifyDataSetChanged();
}
}
}

Adapter:

class TracksAdapter extends ArrayAdapter<Track> {
private final Context context;
private final ArrayList<Track> tracks;
private int currentPage = 0;

public TracksAdapter(Context context,
ArrayList<Track> recentTrackArrayList) {
super(context, 0, recentTrackArrayList);
this.context = context;
this.tracks = recentTrackArrayList;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item,
parent, false);
}

final Track track = tracks.get(position);

final TextView tv = (TextView) convertView
.findViewById(R.id.tv);
// Repeat for other views

tv.setText(track.getName());
// Repeat for other views

//Check if we're at the end of the list
if(position == getCount() - 1) {
currentPage++;
new RecentTracksTask().execute(currentPage);
}

return convertView;
}
}

Infinite listview scroll in android

Try this

MainActivity.java

package com.example.endlesslistview;

import java.util.ArrayList;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ProgressBar;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;

public class MainActivity extends Activity {

ListView lvTest;
int index=0;
ArrayList<ModelClass> model = new ArrayList<ModelClass>();
AdapterClass adapter;
ProgressBar progressbar;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

progressbar = (ProgressBar) findViewById(R.id.progressbar);
lvTest = (ListView) findViewById(R.id.lvTest);
insertData();
adapter = new AdapterClass(MainActivity.this, model);
lvTest.setAdapter(adapter);

lvTest.setOnScrollListener(new EndlessScrollListener());
}

public void insertData(){
for(int i=0;i<20;i++){
model.add(new ModelClass("Data "+index, R.drawable.ic_launcher));
index = index+1;
}
}

public void insertNewData(){
for(int i=0;i<20;i++){
model.add(new ModelClass("Data "+index, R.drawable.ic_launcher));
index = index+1;
}

adapter.notifyDataSetChanged();
}

public class EndlessScrollListener implements OnScrollListener {

private int visibleThreshold = 20;
private int currentPage = 0;
private int previousTotal = 0;
private boolean loading = true;

public EndlessScrollListener() {
}
public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}

@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
currentPage++;
}
}
if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
// I load the next page of gigs using a background task,
// but you can call any function here.
new ShowProgress().execute();
loading = true;
}
}

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

class ShowProgress extends AsyncTask<Void, Void, Void>{

@Override
protected void onPreExecute() {
progressbar.setVisibility(View.VISIBLE);
}

@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub

try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return null;
}

@Override
protected void onPostExecute(Void result) {
progressbar.setVisibility(View.GONE);
insertNewData();
}
}
}

Activity_main.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.endlesslistview.MainActivity" >

<ListView
android:id="@+id/lvTest"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
</ListView>

<ProgressBar
android:id="@+id/progressbar"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="visible" />

</FrameLayout>

AdapterClass.java

package com.example.endlesslistview;
import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class AdapterClass extends BaseAdapter{
Context context;
private static LayoutInflater inflater=null;
ArrayList<ModelClass> model;

public AdapterClass(MainActivity mainActivity, ArrayList<ModelClass> model) {
// TODO Auto-generated constructor stub
this.model = model;
context=mainActivity;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return model.size();
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}

public class Holder
{
TextView tv;
ImageView img;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.row_layout, null);
holder.tv=(TextView) rowView.findViewById(R.id.textView1);
holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
holder.tv.setText(model.get(position).getData());
holder.img.setImageResource(model.get(position).getImage());
rowView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "You Clicked "+model.get(position).getData(), Toast.LENGTH_LONG).show();
}
});
return rowView;
}

}

row_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:layout_gravity="center_vertical"
android:gravity="center_vertical" >

<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:layout_marginRight="10dp" />

</LinearLayout>

ModelClass.java

package com.example.endlesslistview;

public class ModelClass {

String data;
int image;

public ModelClass(String data, int image) {
this.data = data;
this.image = image;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}

}

Flutter ListView.builder creates an infinite scroll. How can I set it to stop at the end of content?

This ended up being pretty easy. Not sure how I missed it from the docs, all I needed to add was an Item count = non-null. In my case, since I am building all of my content in a single Column widget, inside the list-view builder, this is what my builder looks like:

new ListView.builder(
scrollDirection: Axis.vertical,
key: new Key(randomString(20)),
primary: true,
itemCount: 1,
itemBuilder: (BuildContext context, int index) {
return new Column(
children: <Widget>[ .....

I do wonder about this implementation if its a bad pattern. Will ListView.Builder still render each nested children of Component Column, as each children of Column becomes visible?

From the docs: "Creates a scrollable, linear array of widgets that are created on demand.
This constructor is appropriate for list views with a large (or infinite) number of children because the builder is called only for those children that are actually visible."



Related Topics



Leave a reply



Submit