RecyclerView jumps to the top when paging… here is a solution to the problem.
RecyclerView jumps to the top when paging
An attempt was made to implement paging in RecyclerView, but when RecyclerView reached the end and the application started loading new sections of data, RecyclerView jumped to the top of it.
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 !");
}
}
}
});
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);
}
}
});
}
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 gradle files:
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 who can tell me what I did wrong?
Solution
So this question is really stupid! First, I moved these two things to onCreate().
adapter = new OffersAdapter(MainActivity.this, cityList);
cityListRecyclerview.setAdapter(adapter);
And added
adapter.notifyDataSetChanged();
In the loadFromUrl() method, everything now works fine 😀 Maybe if someone has the same problem, then he will see my post 😀