Recycleview pagination not bind adapter android - android

Hello friends i want to integrate pagination in my recycleview so below is my code
in onCreateVIew
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.task_recycle);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setOnScrollListener(new EndlessRecyclerOnScrollListener(mLayoutManager) {
#Override
public void onLoadMore(int current_page) {
if (OnzupApplication.mPendingDatas.size() < total) {
page++;
new getPendingTask(false,true).execute();
}
}
});
if (mAllMethods.check_Internet() == true) {
new getPendingTask(true,false).execute();
} else {
mAllMethods.ShowDialog(getActivity(), "", getString(R.string.net_not_available), "OK");
}
Call AsyncTask
public class getPendingTask extends AsyncTask<Void, Void, Void> {
private boolean showLoading;
boolean pagination;
public getPendingTask(boolean showLoading,boolean page) {
this.showLoading = showLoading;
this.pagination=page;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (showLoading == true) {
mProgressDialog = ProgressDialog.show(getActivity(), "", getString(R.string.loading));
}
}
#Override
protected Void doInBackground(Void... voids) {
mGetPendigTask = (GetAllPendigTask) mPostParseGet.getPendingTask(mGetPendigTask, token, page);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (showLoading == true) {
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
}
try {
if (mPostParseGet.isNetError) {
mAllMethods.ShowNoConnectionDialog(mActivity, mContext, "", getString(R.string.net_not_available), getString(R.string.setting), getString(R.string.cancel));
} else if (mPostParseGet.isOtherError) {
if (!mPostParseGet.isRequestTimeOutError) {
new ActivityHelper(mActivity).sendMail(token);
}
mAllMethods.ShowDialog(mActivity, "", getString(R.string.data_not_found), "OK");
} else {
if (mGetPendigTask.isSuccess() == true) {
mPendingDatas = getData();
total = Integer.parseInt(mGetPendigTask.getTotalitems());
if (mGetPendigTask.getTasks().size() > 0) {
mTextViewNoData.setVisibility(View.GONE);
mRecyclerView.setVisibility(View.VISIBLE);
mAllPendingRecyclerAdapter = new AllPendingRecyclerAdapter(getActivity(), OnzupApplication.mPendingDatas);
if (pagination==false)
{
mRecyclerView.setAdapter(mAllPendingRecyclerAdapter);
}
mAllPendingRecyclerAdapter.notifyDataSetChanged();
} else {
mTextViewNoData.setVisibility(View.VISIBLE);
mRecyclerView.setVisibility(View.GONE);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
When i call above code 1 page is loaded but when i scroll second page data is not loaded any idea how can i solve this?

Because of this line
mAllPendingRecyclerAdapter = new AllPendingRecyclerAdapter(getActivity(), OnzupApplication.mPendingDatas);
You did create the Adapter at the first time, when you use load more function in recyclerview. You should add your data in your own Adapter instead of create the new one

Related

data not showing in recyclerview using notifyDataSetChanged in Retrofit but works in volley

I always use the approach to show the data in recyclerview using Volley is to create Adapter in Oncreate method and then notify after receiving response from volley using notifyDataSetChanged.
I tried to use the same approach in Retrofit but data is not showing in Recyclerview,but if instead of setting adapter in Oncreate method if I set Adapter in retrofit after receiving response from Retrofit then it works perfectly
My question is that
(1) why the data is not showing in Retrofit if i create adapter in Oncreate am i doing something wrong?
(2)Is it a good approach to create adapter in Oncreate and then notifying it after receiving response or shoud I set adapter after getting response?
If I set adapter after getting response like this
#Override
public void onResponse(Call<SubCatModelList> call, Response<SubCatModelList> response) {
Log.d("subcategoryJsonResponse", String.valueOf(response));
Gson gson = new Gson();
String successResponse = gson.toJson(response.body());
Log.d("aaaaaa", String.valueOf(successResponse));
if (response.isSuccessful()) {
subCatModel =response.body().getSubCategories();
Log.d("asaaaaaaa", String.valueOf(subCatModel));
subCategoryAdapter = new SubCategoryAdapter(BinaryCommissionActivity.this, subCatModel);
FixedGridLayoutManager manager = new FixedGridLayoutManager();
manager.setTotalColumnCount(1);
rvBinaryCommission.setLayoutManager(manager);
rvBinaryCommission.setAdapter(subCategoryAdapter);
rvBinaryCommission.addItemDecoration(new DividerItemDecoration(BinaryCommissionActivity.this, DividerItemDecoration.VERTICAL));
}
then every time this line initializes adapter and creates object whenver api hits and i think its a bad approach
subCategoryAdapter = new
SubCategoryAdapter(BinaryCommissionActivity.this, subCatModel);
public class BinaryCommissionActivity extends AppCompatActivity {
int scrollX = 0;
List<SubCatModel> subCatModel = new ArrayList<>();
SubCategoryAdapter subCategoryAdapter;
VolleyCustomClass volleyCustomClass;
#BindView(R.id.toolbarcustom) Toolbar toolbarcustom;
#BindView(R.id.spinner_binary_commission) Spinner spinnerBinaryCommission;
#BindView(R.id.searchViewBinary) SearchView searchViewBinary;
#BindView(R.id.headerScroll) HorizontalScrollView headerScroll;
#BindView(R.id.rvBinaryCommission) RecyclerView rvBinaryCommission;
#BindView(R.id.swipeRefreshBinaryList) SwipeRefreshLayout swipeRefreshBinaryList;
private AlertDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_binary_commission);
ButterKnife.bind(this);
toolbarcustom = findViewById(R.id.toolbarcustom);
setSupportActionBar(toolbarcustom);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Binary Commission");
volleyCustomClass = new VolleyCustomClass(getApplicationContext());
dialog = new SpotsDialog.Builder().setContext(this)
.setMessage("Loading...")
.setCancelable(false).build();
spinnerData();
setUpRecyclerView();
prepareClubData();
recyclerviewScrollListener();
searchFilter();
swipeRefreshBinaryList.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
if (!InternetUtils.checkForInternet(getApplicationContext())) {
swipeRefreshBinaryList.setRefreshing(false);
FancyToast.makeText(getApplicationContext(), "No Internet Connection", FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show();
} else {
prepareClubData();
}
}
});
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return super.onSupportNavigateUp();
}
/**
* Recyclerview ScrollListener
*/
private void recyclerviewScrollListener() {
rvBinaryCommission.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
scrollX += dx;
headerScroll.scrollTo(scrollX, 0);
}
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
});
}
/**
* Search Filter
*/
private void searchFilter() {
searchViewBinary.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
subCategoryAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
subCategoryAdapter.getFilter().filter(newText);
return false;
}
});
}
/**
* Adding data to spinner
*/
private void spinnerData() {
List<String> show_entries = new ArrayList<String>();
show_entries.add("5");
show_entries.add("10");
show_entries.add("15");
show_entries.add("20");
show_entries.add("All");
ArrayAdapter<String> dataAdapterShowEntries = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, show_entries);
dataAdapterShowEntries.setDropDownViewResource(R.layout.layout_spinner_item);
spinnerBinaryCommission.setAdapter(dataAdapterShowEntries);
spinnerBinaryCommission.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
Object item = adapterView.getItemAtPosition(position);
if (item != null) {
// Toast.makeText(getContext(), item.toString(), Toast.LENGTH_SHORT).show();
}
// Toast.makeText(getContext(), "Selected", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
// TODO Auto-generated method stub
}
});
}
private void prepareClubData() {
if (!InternetUtils.checkForInternet(getApplicationContext())) {
FancyToast.makeText(getApplicationContext(), "No Internet Connection", FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show();
return;
} else {
dialog.show();
if (subCatModel != null) {
subCatModel.clear();
}
/**
* Volley
*/
/* volleyCustomClass.callGetServer(URLs.subcategoryURL, new VolleyCallback() {
#Override
public void onSuccess(String response) {
Log.d("subcategoryJsonResponse", response);
try {
JSONObject obj = new JSONObject(response);
JSONArray productArray = obj.getJSONArray("sub-categories");
for (int i = 0; i < productArray.length(); i++) {
JSONObject productObject = productArray.getJSONObject(i);
SubCatModel subCatModelClass = new SubCatModel();
subCatModelClass.setSubcategoriesId(productObject.getString("Subcategories-Id"));
subCatModelClass.setCategoriesId(productObject.getString("categories-Id"));
subCatModelClass.setSubcategoriesName(productObject.getString("Subcategories-Name"));
subCatModel.add(subCatModelClass);
Log.d("subCategoryArraylist", String.valueOf(subCatModel));
}
dialog.dismiss();
subCategoryAdapter.notifyDataSetChanged();
swipeRefreshBinaryList.setRefreshing(false);
} catch (JSONException e) {
e.printStackTrace();
dialog.dismiss();
}
}
#Override
public void onError(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
swipeRefreshBinaryList.setRefreshing(false);
}
});*/
/**
* Retrofit
*/
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<SubCatModelList> call = apiService.getList();
call.enqueue(new Callback<SubCatModelList>() {
#Override
public void onResponse(Call<SubCatModelList> call, Response<SubCatModelList> response) {
Log.d("subcategoryJsonResponse", String.valueOf(response));
Gson gson = new Gson();
String successResponse = gson.toJson(response.body());
Log.d("aaaaaa", String.valueOf(successResponse));
if (response.isSuccessful()) {
subCatModel =response.body().getSubCategories();
Log.d("asaaaaaaa", String.valueOf(subCatModel));
}
dialog.dismiss();
subCategoryAdapter.notifyDataSetChanged();
swipeRefreshBinaryList.setRefreshing(false);
}
#Override
public void onFailure(Call<SubCatModelList> call, Throwable t) {
swipeRefreshBinaryList.setRefreshing(false);
}
});
}
}
/**
* Handles RecyclerView for the action
*/
private void setUpRecyclerView() {
subCategoryAdapter = new SubCategoryAdapter(BinaryCommissionActivity.this, subCatModel);
FixedGridLayoutManager manager = new FixedGridLayoutManager();
manager.setTotalColumnCount(1);
rvBinaryCommission.setLayoutManager(manager);
rvBinaryCommission.setAdapter(subCategoryAdapter);
rvBinaryCommission.addItemDecoration(new DividerItemDecoration(BinaryCommissionActivity.this, DividerItemDecoration.VERTICAL));
}
}
Instead of initializing adapter everytime, you can use: (inside adapter class)
public void setItems(List<String> myList) { // Let's say it's List of Strings
this.myList = myList;
notifyDataSetChanged();
}
And everytime you change List with your data to display (in your case inside of onResponse()) you just call 'setItems()' on your adapter.

Paging library network error when data is loaded

I am working with paging library and I am struggling with the LiveData PagedList.
My paginated list is working properly but there is an scenario where it is not. I have RecyclerView + SwipeRefreshLayout when data is already shown in the list and I disable network and I try to swipe refresh all the data in the list is removed. How can I avoid that?
public class InterestsViewModel extends ViewModel {
private LiveData<PagedList<InterestItem>> mListInterests;
private CompositeDisposable mCompositeDisposable = new CompositeDisposable();
private static final int PAGE_SIZE = 15;
private GroupsInterestsDataSourceFactory mGroupsInterestsDataSourceFactory;
public InterestsViewModel() {
Executor executor = Executors.newFixedThreadPool(5);
mGroupsInterestsDataSourceFactory = new GroupsInterestsDataSourceFactory(mCompositeDisposable);
PagedList.Config config = new PagedList.Config.Builder()
.setPageSize(PAGE_SIZE)
.setInitialLoadSizeHint(PAGE_SIZE)
.setEnablePlaceholders(true)
.build();
mListInterests = new LivePagedListBuilder<>(mGroupsInterestsDataSourceFactory,config)
.setFetchExecutor(executor)
.build();
}
public void retry() {
mGroupsInterestsDataSourceFactory.getGroupsInterestsDataSource().getValue().retry();
}
public void refresh() {
mGroupsInterestsDataSourceFactory.getGroupsInterestsDataSource().getValue().invalidate();
}
public LiveData<NetworkState> getNetworkState() {
return Transformations.switchMap(mGroupsInterestsDataSourceFactory.getGroupsInterestsDataSource(), new Function<GroupsInterestsDataSource, LiveData<NetworkState>>() {
#Override
public LiveData<NetworkState> apply(GroupsInterestsDataSource input) {
return input.getNetworkState();
}
});
}
public LiveData<NetworkState> getRefreshState() {
return Transformations.switchMap(mGroupsInterestsDataSourceFactory.getGroupsInterestsDataSource(), new Function<GroupsInterestsDataSource, LiveData<NetworkState>>() {
#Override
public LiveData<NetworkState> apply(GroupsInterestsDataSource input) {
return input.getInitialLoad();
}
});
}
public LiveData<PagedList<InterestItem>> getListInterests() {
return mListInterests;
}
#Override
protected void onCleared() {
super.onCleared();
mCompositeDisposable.dispose();
}
}
From the the fragment:
private void initAdapter() {
mAdapter = new InterestsAdapter(this);
mListInterest.setAdapter(mAdapter);
mInterestsViewModel.getListInterests().observe(this, new Observer<PagedList<InterestItem>>() {
#Override
public void onChanged(#Nullable PagedList<InterestItem> interestItems) {
mAdapter.submitList(interestItems);
}
});
mInterestsViewModel.getNetworkState().observe(this, new Observer<NetworkState>() {
#Override
public void onChanged(#Nullable NetworkState networkState) {
mAdapter.setNetworkState(networkState);
}
});
mInterestsViewModel.getRefreshState().observe(this, new Observer<NetworkState>() {
#Override
public void onChanged(#Nullable NetworkState networkState) {
if (networkState != null) {
if (mAdapter.getCurrentList() != null) {
if (networkState.getStatus()
== NetworkState.LOADED.getStatus() || networkState.getStatus()
== Status.FAILED)
mIsRefreshing = false;
if (mAdapter.getCurrentList().size() > 0) {
mSwipeRLInterests.setRefreshing(networkState.getStatus()
== NetworkState.LOADING.getStatus());
}
}
setInitialLoadingState(networkState);
}
}
});
}
#Override
public void retry() {
mInterestsViewModel.retry();
}
private void initSwipeToRefresh() {
mSwipeRLInterests.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mIsRefreshing = true;
mInterestsViewModel.refresh();
}
});
mSwipeRLInterests.setColorSchemeColors(getResources().getColor(R.color.colorPrimaryDark)
, getResources().getColor(R.color.colorPrimary)
, getResources().getColor(R.color.colorPrimaryDark));
}

how to prevent the footerview show when pulltorefresh load all data?

I use pulltorefreshListview in my project, I set Mode.Both. I want the result when I pull from end for loading more,and scroll the end ,already load all data ,I hope the footerview hide. but now when I scroll the listview to end ,the footerview is showing, How can I for that?
private void pullRefresh() {
morelist.setOnRefreshListener(new OnRefreshListener<ListView>() {
#Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
if (refreshView.isShownHeader()) {
//refresh
new GetDataTask().execute();
}else if (refreshView.isShownFooter()) {
//load more
number = number+20;
new GetDataTask().execute();
}
}
});
}
private class GetDataTask extends AsyncTask<Void, Void, String[]> {
#Override
protected String[] doInBackground(Void... params) {
try {
if (isDown) {
getData(number,"-1");
} else {
getData(number,"1");
}
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] result) {
morelist.onRefreshComplete();
super.onPostExecute(result);
}
}

Cannot resolve symbol 'adapter'

I receive an error with the following code. I don't understand why, but adapter.notifyDataSetChanged(); doesn't work. The message of error is: "cannot resolve symbol 'adapter'".
final String URL = "http://example....";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rv = (RecyclerView) findViewById(R.id.rv);
....
public class PrintA extends AsyncTask<String, String, List<Model>> {
....
#Override
protected void onPostExecute(final List<MyModel> result) {
super.onPostExecute(result);
if (result != null) {
MyAdapter adapter = new MyAdapter(result);
rv.setAdapter(adapter);
} else {
Toast.makeText(getApplicationContext(), "no internet",
}
}
}
new PrintA().execute(URL);
rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
....
public class PrintB extends AsyncTask<String, String, List<Model>> {
....
#Override
protected void onPostExecute(final List<MyModel> result) {
super.onPostExecute(result);
if (result != null) {
....
adapter.notifyDataSetChanged();
} else {
Toast.makeText(getApplicationContext(), "can't add",
}
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
....
new PrintB().execute(URL);
}
}
}
}
MyAdapter adapter = new MyAdapter(result);
replace this by
adapter = new MyAdapter(result);
and declare this in Global
MyAdapter adapter;
like this
MyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {

Recyclerview not refreshing after returning to fragment

i have favorites fragment with recyclerview , the data is showing well
but when i click on a reyclerview item and remove it from favorites when pressing back to the favorites fragment is still showing in the recylerview , i know that the probleme is recyclerview is not refrishing because when i restart the app the item is removed , i tried notifydatasetchanged but its not working
here is oncreateview and onresume of the favorites fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView= inflater.inflate(R.layout.fragment_favourites, container, false);
activity=getActivity();
tinydb = new TinyDB(activity);
liststorieshits=(RecyclerView) rootView.findViewById(R.id.lsv_cat_item_fav);
liststorieshits.setLayoutManager(new LinearLayoutManager(getActivity()));
rippleView = ((RippleView) rootView.findViewById(R.id.rect_fav));
liststorieshits.setHasFixedSize(true);
liststorieshits.addItemDecoration(new VerticalDividerItemDecoration.Builder(getActivity()).build());
mAdapter=new FavoritesAdapter(getActivity(),itemsList);
liststorieshits.setAdapter(mAdapter);
progress = new ProgressDialog(getActivity());
progress.setTitle("Loading");
progress.setMessage("Wait while loading Stories");
progress.show();
RestAdapter restAdapter=new RestAdapter.Builder().setEndpoint(getString(R.string.categories_feed)).build();
final CategoriesApiInterface categoriesApiInterface=restAdapter.create(CategoriesApiInterface.class);
idlist2=tinydb.getListInt("strid");
int ab=0;
for(int i=0;i<idlist2.size();i++){
ab=idlist2.get(i);
categoriesApiInterface.getStreams3(ab, new Callback<List<Stories>>() {
#Override
public void success(List<Stories> stories, Response response) {
progress.dismiss();
if (stories == null || stories.isEmpty()) {
return;
}
for (Stories stories1 : stories) {
itemsList.add(stories1);
}
mAdapter.notifyDataSetChanged();
Log.e("Stories", "krb :" + itemsList.size());
}
#Override
public void failure(RetrofitError error) {
progress.dismiss();
Log.e("Stories", "Retrofit error " + error.getMessage());
}
});
}
return rootView;
}
#Override
public void onResume() {
super.onResume();
mAdapter.notifyDataSetChanged();
}
You may try this way to update your RecycleView:
#Override
public void onResume() {
super.onResume();
itemsList.clear();
idlist2=tinydb.getListInt("strid");
int ab=0;
for(int i=0;i<idlist2.size();i++){
ab=idlist2.get(i);
categoriesApiInterface.getStreams3(ab, new Callback<List<Stories>>() {
#Override
public void success(List<Stories> stories, Response response) {
progress.dismiss();
if (stories == null || stories.isEmpty()) {
return;
}
for (Stories stories1 : stories) {
itemsList.add(stories1);
}
mAdapter.notifyDataSetChanged();
Log.e("Stories", "krb :" + itemsList.size());
}
#Override
public void failure(RetrofitError error) {
progress.dismiss();
Log.e("Stories", "Retrofit error " + error.getMessage());
}
});
}
mAdapter = new FavoritesAdapter(getActivity(),itemsList);
liststorieshits.setAdapter(mAdapter);
}
ADDED
You may make update() for updating data in separate function, like this:
private void update() {
itemsList.clear();
idlist2=tinydb.getListInt("strid");
int ab=0;
for(int i=0;i<idlist2.size();i++){
ab=idlist2.get(i);
categoriesApiInterface.getStreams3(ab, new Callback<List<Stories>>() {
#Override
public void success(List<Stories> stories, Response response) {
progress.dismiss();
if (stories == null || stories.isEmpty()) {
return;
}
for (Stories stories1 : stories) {
itemsList.add(stories1);
}
mAdapter.notifyDataSetChanged();
Log.e("Stories", "krb :" + itemsList.size());
}
#Override
public void failure(RetrofitError error) {
progress.dismiss();
Log.e("Stories", "Retrofit error " + error.getMessage());
}
});
}
mAdapter = new FavoritesAdapter(getActivity(),itemsList);
liststorieshits.setAdapter(mAdapter);
}
And use it:
#Override
public void onResume() {
super.onResume();
update();
}
override fun onResume() {
super.onResume()
binding.mRecyclerView.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
}

Categories

Resources