Home > Blockchain >  Delete item in recyclerview works only once
Delete item in recyclerview works only once

Time:01-23

When I delete an item from the recyclerview, I am no longer able to delete another item. When I make an item I am also unable to delete that item and any other item in the recyclerview.

Below is the code.

Home.java

@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.home_activity);

    itemImage = findViewById(R.id.image_holder);
    itemName = findViewById(R.id.add_item_name);
    itemPrice = findViewById(R.id.add_price);
    itemDesc = findViewById(R.id.add_desc);

    // Initialize Firebase Auth
    mAuth = FirebaseAuth.getInstance();

    addPhotoButton = findViewById(R.id.getCameraBtn);
    addFileButton = findViewById(R.id.getGalleryBtn);

    imageView = findViewById(R.id.image_holder);

    addPhotoButton.setOnClickListener(this);
    addFileButton.setOnClickListener(this);

    itemList = new ArrayList<Item>();

    // add item for testing
    itemList.add(new Item(R.drawable.ic_logo, "Baby Stroller", "A stroller for baby", "59.99"));

    recyclerView = findViewById(R.id.recyclerView);
    recyclerView.setHasFixedSize(true);

    layoutManager = new LinearLayoutManager(this);
    adapter = new ItemAdapter(itemList);


    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setAdapter(adapter);

    adapter.setOnItemClickListener(new ItemAdapter.OnItemClickListener() {
        @Override
        public void onDeleteClick(int position) {
            removeItem(position);
        }

        @Override
        public void onEditClick(int position) {
            editItem(position);
        }
    });
}

// log out back to start page
public void goToStart(View view){
    Intent intent = new Intent(this, MainActivity.class);
    startActivity(intent);
}

@Override
public void onClick(View view) {
    switch (view.getId()) {

        case R.id.getCameraBtn:
            //post a photo from the camera
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(takePictureIntent, CAMERA_CODE);

            break;

        case R.id.getGalleryBtn:
            //post an image

            Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
            galleryIntent.setType("image/*"); //anything that is image related
            startActivityForResult(galleryIntent, GALLERY_CODE);

            break;
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == GALLERY_CODE && resultCode == RESULT_OK) {
        if (data != null) {
            imageUri = data.getData(); //we have the actual path
            imageView.setImageURI(imageUri); //show image

        }
    } else if (requestCode == CAMERA_CODE && resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        Bitmap imageBitmap = (Bitmap) extras.get("data");
        imageView.setImageBitmap(imageBitmap);
    }
}

public void addItem(View view){
    if(itemName.getText().toString().trim().length() != 0 || itemPrice.getText().toString().trim().length() != 0 || itemDesc.getText().toString().trim().length() != 0){
        itemList.add(new Item(R.drawable.ic_logo, itemName.getText().toString(), itemPrice.getText().toString(), itemDesc.getText().toString()));
        adapter = new ItemAdapter(itemList);
        recyclerView.setAdapter(adapter);

        itemName.setText("");
        itemPrice.setText("");
        itemDesc.setText("");

    }
    else{
        Toast.makeText(Home.this, "All fields must be filled when creating a new item.",
                Toast.LENGTH_LONG).show();
    }

}

public void removeItem(int position){
    itemList.remove(position);
    adapter.notifyItemChanged(position);
}

ItemAdapter.java

public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder>{

private ArrayList<Item> ItemList;
private OnItemClickListener Listener;

public void setOnItemClickListener(OnItemClickListener listener) {Listener = listener;}

public interface OnItemClickListener{
    void onDeleteClick(int position);
    
}

public static class ViewHolder extends RecyclerView.ViewHolder{
    public ImageView item_image;
    public TextView item_name;
    public TextView item_desc;
    public TextView item_price;

    public ImageView deleteBtn;
    public ImageView editBtn;

    public ViewHolder(@NonNull View itemView, OnItemClickListener listener) {
        super(itemView);

        item_image = itemView.findViewById(R.id.item_image);
        item_name = itemView.findViewById(R.id.item_name);
        item_desc = itemView.findViewById(R.id.desc);
        item_price = itemView.findViewById(R.id.price);

        deleteBtn = itemView.findViewById(R.id.delete_item);
        editBtn = itemView.findViewById(R.id.edit_item);

        deleteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(listener != null){
                    int position = getAdapterPosition();
                    if (position != RecyclerView.NO_POSITION){
                        listener.onDeleteClick(position);
                    }
                }
            }
        });

        
    }
}

public ItemAdapter(ArrayList<Item> itemList) {ItemList = itemList;}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_items, parent, false);
    ViewHolder vh = new ViewHolder(v, Listener);

    return vh;
}

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
    Item currentItem = ItemList.get(position);
    holder.item_image.setImageResource(currentItem.getItemImage());
    holder.item_name.setText(currentItem.getItemName());
    holder.item_desc.setText(currentItem.getItemDesc());
    holder.item_price.setText(currentItem.getItemPrice());
}

@Override
public int getItemCount() {
    return ItemList.size();
}

}

Item.java

public class Item {
private int itemImage;
private String itemName;
private String itemDesc;
private String itemPrice;

public Item(int itemImage, String itemName, String itemDesc, String itemPrice){
    this.itemImage = itemImage;
    this.itemName = itemName;
    this.itemDesc = itemDesc;
    this.itemPrice = itemPrice;
}

public int getItemImage(){return itemImage;}

public String getItemName(){return itemName;}

public String getItemDesc(){return itemDesc;}

public String getItemPrice(){return itemPrice;}

}

When the user clicks the delete button, it will work the first time and remove that particular item but when another item needs to be removed, the button is not responding. The same happens when the user adds an item and is unable to delete any items. Not really sure what could cause this. Thanks.

Edit: The delete function works correctly when I hardcode items into the recyclerview. It is only when adding a new item, it doesn't work anymore including the hardcoded items.

CodePudding user response:

You are telling the adapter that one item is changed, instead of that use:

notifyDataSetChanged()

this should reload all items

CodePudding user response:

In Home.java, you are setting the click listener:

adapter.setOnItemClickListener(new ItemAdapter.OnItemClickListener() {...}

If addItem(), you are creating a new adapter:

adapter = new ItemAdapter(itemList);

The problem is that you never set a click listener on this new adapter.

I would consider not creating a new adapter but calling a notify method to alert the adapter to a new item.

  • Related