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)
}
Related
So I have a app where I am displaying the products list from the database using a Recycler View.
There is delete button beside each item which is working fine.
And there is a scan item button which opens a BARCODE SCANNER which on succesfull scanning adds the new product to the database and goes back to the Recycler View display is supposed to refresh the view and display the new Item.
but I am having problem with refreshing the recycler view on adding a new Product.
there is also a delete product function which works perfectly so I tried to do the add item method the same way, but the recycler view doesn't refresh.
UserPage activity
public class UserPage extends AppCompatActivity implements ProductAdaptar.clickedItem {
Toolbar toolbar;
RecyclerView recyclerView;
String rfidNo;
public static String barcode;
Button scanItem;
Button payBill;
TextView total;
ProductAdaptar productAdaptar;
Call<List<UserLoginResp>> productList;
List<UserLoginResp> productListsItems = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_page);
toolbar=findViewById(R.id.toolbar);
recyclerView=findViewById(R.id.recyclerview);
scanItem = findViewById(R.id.scanItem);
payBill = findViewById(R.id.payBill);
total = findViewById(R.id.total);
scanItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),ScannerView.class).putExtra("rfid",rfidNo));
}
});
payBill.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkout();
}
});
LinearLayoutManager manager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(manager);
recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
productAdaptar = new ProductAdaptar(this::clickedItem, this);
Intent intent =getIntent();
if(intent.getExtras()!=null){
rfidNo= intent.getStringExtra("rfid");
}
getAllProducts(rfidNo);
}
public void getAllProducts(String rfidno){
LinearLayoutManager manager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(manager);
productAdaptar = new ProductAdaptar(this::clickedItem,this);
productList= ApiClient.getUserPageService().getCartItems(rfidno);
productList.enqueue(new Callback<List<UserLoginResp>>() {
#Override
public void onResponse(Call<List<UserLoginResp>> call, Response<List<UserLoginResp>> response) {
if (response.isSuccessful()) {
productListsItems = response.body();
productAdaptar.setData(productListsItems);
RecyclerView recyclerView = findViewById(R.id.recyclerview);
recyclerView.setAdapter(productAdaptar);
getTotal();
}
}
#Override
public void onFailure(Call<List<UserLoginResp>> call, Throwable t) {
Log.e("listfailed",t.getLocalizedMessage());
}
});
}
public void getTotal(){
Call<getBill> bill = ApiClient.getUserPageService().getBill(rfidNo);
bill.enqueue(new Callback<getBill>() {
#Override
public void onResponse(Call<getBill> call, Response<getBill> response) {
if(response.isSuccessful()){
getBill getBill = response.body();
String bill = String.valueOf(getBill.getBill());
total.setText(bill);
}
}
#Override
public void onFailure(Call<getBill> call, Throwable t) {
Log.e("bill error",""+t);
}
});
}
public void checkout(){
Call<String> payment= APIClientString.getUserPageService().checkout(rfidNo);
payment.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if(response.isSuccessful()){
getAllProducts(rfidNo);
Toast.makeText(UserPage.this, "Payment Successful", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.e("paymentfail",""+t);
}
});
}
#Override
public void clickedItem(UserLoginResp userLoginResp) {
Log.e("clicked prodcut", userLoginResp.toString());
}
}
ScannerView Class
enter #Override
public void handleResult(Result rawResult) {
barcode = rawResult.getText();
if(addItem(barcode,rfidNo)) {
userPage.getAllProducts(rfidNo);
}
onBackPressed();
}
public boolean addItem(String barcode,String rfidNo){
final boolean[] res = {false};
Call<String> resp = APIClientString.getUserPageService().addProduct(barcode,rfidNo);
resp.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if(response.isSuccessful()){
Toast.makeText(ScannerView.this, response.body().toString(), Toast.LENGTH_SHORT).show();
res[0] =true;
}
}
This is the scanner class which is suppose to call the call the getAllproducts function from the UserPage Activity to refresh the view. It shows no error but the recycler view doesn't get updated.
This is the Adapter Class
public class ProductAdaptar extends RecyclerView.Adapter<ProductAdaptar.ProductAdaptarVH> {
private List<UserLoginResp> productListItems;
private UserPage context;
private clickedItem clickedItem;
public ProductAdaptar(clickedItem clickedItem, UserPage activity) {
this.clickedItem = clickedItem;
this.context= activity;
}
public void setData(List<UserLoginResp> productListItems) {
this.productListItems = productListItems;
notifyDataSetChanged();
}
#NonNull
#Override
public ProductAdaptarVH onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new ProductAdaptar.ProductAdaptarVH(LayoutInflater.
from(context).inflate(R.layout.row_products,parent,false));
}
#Override
public void onBindViewHolder(#NonNull ProductAdaptarVH holder, int position) {
UserLoginResp userLoginResp = productListItems.get(position);
String pName = userLoginResp.getProductName();
String pQuan = userLoginResp.getQuantity();
String pPrice = userLoginResp.getProductPrice();
String pBarcode = userLoginResp.getProductID();
String userID = userLoginResp.getUserID();
holder.pName.setText(pName);
holder.pQuan.setText(pQuan);
holder.pPrice.setText(pPrice);
holder.delProdcut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
delProduct(userID,pBarcode);
}
});
holder.moreDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
public interface clickedItem{
public void clickedItem(UserLoginResp userLoginResp);
}
public void delProduct(String userID, String pBarcode){
Call<String> res = APIClientString.getUserPageService().deleteProduct(pBarcode,userID);
res.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if(response.isSuccessful()){
Toast.makeText(context, response.body().toString(), Toast.LENGTH_SHORT).show();
context.getAllProducts(userID);
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.e("deletefailed",""+t);
}
});
}
#Override
public int getItemCount() {
return productListItems.size();
}
public static class ProductAdaptarVH extends RecyclerView.ViewHolder {
TextView pName;
TextView pQuan;
TextView pPrice;
Button delProdcut;
Button moreDetails;
public ProductAdaptarVH(#NonNull View itemView) {
super(itemView);
pName=itemView.findViewById(R.id.pName);
pQuan=itemView.findViewById(R.id.pQuantity);
pPrice=itemView.findViewById(R.id.pPrice);
delProdcut=itemView.findViewById(R.id.delProduct);
moreDetails=itemView.findViewById(R.id.moreDetails);
}
}
}
In this Product Apdapter there is a delete product item function
holder.delProdcut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
delProduct(userID,pBarcode);
}
});
public void delProduct(String userID, String pBarcode){
Call<String> res = APIClientString.getUserPageService().deleteProduct(pBarcode,userID);
res.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if(response.isSuccessful()){
Toast.makeText(context, response.body().toString(), Toast.LENGTH_SHORT).show();
context.getAllProducts(userID);
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.e("deletefailed",""+t);
}
});
}
Which also calls the getProduts function from UserPage activity and it works perfectly fine but the AddItem function doesn't refresh the view.
The Retrofit APIs are working completly fine too, the problem is only with refreshing the recycler view display on Item Add.
I am new to android coding so I can't seem to understand how to do it.
As you are refreshing your adapter using getAllProducts() method but it is being called in onCreate(). Now whenever you start a ScannerView activity, UserPage activity gets paused and then started (not created) when ScannerView activity finishes. So, you should call getAllProducts() in onStart() method like this:
#Override
protected void onStart() {
super.onStart();
Intent intent = getIntent();
if (intent.getExtras() != null) {
rfidNo = intent.getStringExtra("rfid");
}
getAllProducts(rfidNo);
}
This is the code of my fragment, when i created a recyclerview, when i can see a list if I click on I can see detail in antoher page, but when I come back I can't see the list.
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SharedPreferences pref = getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
adapter = new PlatformAdapter(data);
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
//recyclerView.setAdapter(adapter);
if (pref.getBoolean("firstTime", true)) {
RequestVolley.getInstance(getContext())
.doGetRequest("http://www....json", new RequestVolley.OnCompleteCallback() {
#Override
public void onCompleted(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.optJSONObject(i);
if (object != null) {
data.add(Platform.parseJSON(object));
}
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
new Thread(new Runnable() {
#Override
public void run() {
DB.getInstance(getContext()).getPlatformDao().insert(data);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
}
});
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("firstTime", false);
editor.apply();
final PlatformAdapter adapter = new PlatformAdapter(data);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
recyclerView.setAdapter(adapter);
}
});
}
}).start();
}
if(pref.getBoolean("firstTime",false)){
new Thread(new Runnable() {
#Override
public void run() {
data.addAll(DB.getInstance(getContext()).getPlatformDao().findAll());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
}
});
final PlatformAdapter adapter = new PlatformAdapter(data);
recyclerView.post(new Runnable() {
#Override
public void run() {
recyclerView.setAdapter(adapter);
}
});
}
}).start();
}
}
}
this is the code of my app in the point of inserto or reload from roomDatabase, the first time I oper the page it's ok, but the second time I can see only a white page.Why? I dont'have any error.
Why it isn't on the DB, or it isn't reload?
This is my Dao
#Dao
public interface PlatformDao {
#Insert(onConflict = OnConflictStrategy.REPLACE)
public void insertOne(Platform platform);
#Insert(onConflict=OnConflictStrategy.REPLACE)
public void insert(List<Platform> platforms);
#Insert(onConflict=OnConflictStrategy.REPLACE)
public void insertVarArgs(Platform...platforms);
#Update
public void update(Platform platform);
#Delete
public void delete(Platform platform);
#Query("SELECT * FROM platforms")
public List<Platform> findAll();
#Query("SELECT * FROM platforms WHERE cdenominazione__=:cdenominazione__")
public Platform findById(String cdenominazione__);
}
When you add the fragment are you doing an add or a replace? Aso are you adding the fragment to the backstack?
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.
i have a fragment that contains a recyclerview which needs pagination
so once it reach end of it it will call the API to retrieve a new data and append to the list.
in addition i had just added a swipeRefreshLayout to the view once the user swipe for a refresh it will clear the recyclerview and add the data again
Now the problem is that the adapter is unable to detect end of recyclerview once the swipe to refresh is called
Code Below:
newsSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
generateNews(1);
}
});
adapterNews.setLoadMore(new ToLoadMore() {
#Override
public void LoadMore() {
if (next_offset != 0) {
newsList.add(null);
adapterNews.notifyItemInserted(newsList.size() - 1);
newsApi.GetNews(Constant.ACCESSTOKEN, next_offset).enqueue(new Callback<NewsData>() {
#Override
public void onResponse(Call<NewsData> call, Response<NewsData> response) {
Log.d("PAGINATION", "PAGINATION");
newsList.remove(newsList.size() - 1);
adapterNews.notifyItemRemoved(newsList.size());
newsList.addAll(response.body().getNews());
next_offset = response.body().getNextOffset();
adapterNews.notifyDataSetChanged();
adapterNews.setLoaded();
}
#Override
public void onFailure(Call<NewsData> call, Throwable t) {
}
});
}
}
});
generateNews(1);
return v;
}
the function which generate news is the below
private void generateNews(final int offset) {
newsApi.GetNews(Constant.ACCESSTOKEN, offset).enqueue(new Callback<NewsData>() {
#Override
public void onResponse(Call<NewsData> call, Response<NewsData> response) {
newsList.clear();
newsList.addAll(response.body().getNews());
next_offset = response.body().getNextOffset();
if (newsSwipeRefreshLayout.isRefreshing()) {
newsSwipeRefreshLayout.setRefreshing(false);
}
news_progressbar.setVisibility(View.GONE);
news_progressText.setVisibility(View.GONE);
newsRecyclerView.setVisibility(View.VISIBLE);
adapterNews.notifyDataSetChanged();
}
#Override
public void onFailure(Call<NewsData> call, Throwable t) {
snackbar = Snackbar.make(getView(), "No Internet Connection", Snackbar.LENGTH_INDEFINITE).setAction("Close", new View.OnClickListener() {
#Override
public void onClick(View v) {
snackbar.dismiss();
generateNews(1);
}
});
snackbar.show();
if (newsSwipeRefreshLayout.isRefreshing()) {
newsSwipeRefreshLayout.setRefreshing(false);
}
}
});
}
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