Reputation: 628
Trying to implement pagination in RecyclerView, but when the RecyclerView reaches it's end and applications starts loading new portion of data the RecyclerView jumps to it's top.
cityListRecyclerview = (RecyclerView) findViewById(R.id.recyclerView);
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
cityListRecyclerview.setLayoutManager(linearLayoutManager);
loadFromUrl();
cityListRecyclerview.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
visibleItemCount = linearLayoutManager.getChildCount();
totalItemCount = linearLayoutManager.getItemCount();
pastVisiblesItems = linearLayoutManager.findFirstVisibleItemPosition();
if (loading) {
if ( (visibleItemCount+pastVisiblesItems) >= totalItemCount) {
loading = false;
page++;
url += Api.OFFSET_URL + String.valueOf(page);
loadFromUrl();
Log.v("LIST", "Last Item Wow !");
}
}
}
});
The loadFromUrl() method:
public void loadFromUrl() {
Ion.with(MainActivity.this)
.load(url)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
@Override
public void onCompleted(Exception e, JsonObject jsonObject) {
progressDialog.dismiss();
JsonArray jsonArray = jsonObject.getAsJsonArray("flats");
jsonObjectToPass = jsonArray;
for(int i = 0; i < jsonArray.size(); i++) {
JsonElement obj = jsonArray.get(i);
JsonObject jsonObject1 = obj.getAsJsonObject();
............ here parsing JSON object and nothing interesting
adapter = new OffersAdapter(MainActivity.this, cityList);
adapter.setClickListener(MainActivity.this);
loading = true;
cityListRecyclerview.setAdapter(adapter);
}
}
});
}
The XML file:
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
And the gradle file:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.0.0'
compile 'com.google.android.gms:play-services:7.0.0'}
So can anyone tell what am I doing wrong?
Upvotes: 4
Views: 2145
Reputation: 628
So the problem was really stupid! First i moved this two things into onCreate()
adapter = new OffersAdapter(MainActivity.this, cityList);
cityListRecyclerview.setAdapter(adapter);
And added
adapter.notifyDataSetChanged();
In loadFromUrl() method, and now everything works well :D Maybe if someone will have the same problem, then he'll see my post :D
Upvotes: 4