Reputation: 43
I'm adding items to a list in a Recyclerview Adapter via an input dialog. when a user enters a value in a textfield and clicks on submit button, I want the entered value to be added to a list which is declared public in a fragment such that if I go to the fragment and click on showListSize button, I should see the size of the list(in fragment) being greater than 0;
Adding an item to the list in RecyclerView works but the size cannot exceed 1. What could I be doing wrong.
Here is a sample code:
//Adapter, constructor and variables declaration
//on create viewholder
@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
List<Item2> valuesList = new ArrayList<Item2>(child.get(groupname));
childSize = valuesList.size();
Log.i("List size", String.valueOf(childSize));
if (childSize > 0){
//final String childText = (String) getChild(groupPosition,position);
final Item2 item = valuesList.get(position);
holder.name.setText(item.getItemName());
//holder.itemImage.setImageResource(Integer.parseInt(item.getImageUrl()));
holder.price.setText(String.valueOf(item.getPrice()));
holder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.select_quantity);
Button button_submit = dialog.findViewById(R.id.btn_submit);
final EditText edQuantity = dialog.findViewById(R.id.txt_quantity);
edQuantity.setText("0");
button_submit.setOnClickListener(new View.OnClickListener() {
float totalPrice = 0;
@Override
public void onClick(View view) {
String quantity = edQuantity.getText().toString();
totalPrice = Float.parseFloat(quantity) * Float.parseFloat(item.getPrice());
myLocal.add(new CartItem(quantity, item.getItemName(), item.getPrice(),String.valueOf(totalPrice)));
AllProducts myProducts = new AllProducts(); //this is the fragment
myProducts.theSelected.add(new CartItem(quantity,item.getItemName(), item.getPrice(),String.valueOf(totalPrice)));
Log.i("size(Recycler)",String.valueOf(myProducts.theSelected.size())); //this is ok returns 1
dialog.dismiss();
}
});
dialog.show();
AllProducts fragment
public List<CartItem> theSelected = new ArrayList<CartItem>();//list declaration
btnShowListSize.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.i("list(AllProducts)", String.valueOf(theSelected.size()));//returns 0
}
});
Upvotes: 1
Views: 36
Reputation: 43
I defined a global ArrayList like this
private List<Items> selectedItems = new ArrayList<>();
Then a method to add items, still in global class
public void addItems(Item item) {
this.selectedItems.add(item);
}
Then in a class somewhere in the project:
final Globals myGlobals = Globals.getInstance();
Item myItem = new Item("var1", "var2", "var3");
myGlobals.addItems(myItem);
Upvotes: 2