Home > Enterprise >  Andriod Retrofit 2: Refreshing Recycler View From from another Activity
Andriod Retrofit 2: Refreshing Recycler View From from another Activity

Time:06-01

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.

CodePudding user response:

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);
    }
  • Related