Using button to delete selected item in Listview w/ ArrayAdapter

I’ve been working with Java for a few months but new to Android. This is a recipe holder app.

I have an ArrayAdapter set on a ListView and am needing to select an item in the ListView and delete it with a Button (I’ve already successfully set up adding of Strings to the Listview). I’m using an ArrayList for the list used to store Ingredient objects rather than a regular array. I’m attempting to use AdapterView.onSelectedItemListener to identify a user selection in the ListView and then use the Button to delete the selected item. For the Button, I’m implementing Button.onClickItemListener.

To get the list items into the ListView I’m using a dialog. I’m using an interface to send the string input from the dialog to the ListView in RecipeFragmentNew. I haven’t been having issues getting the Strings from the dialog to RecipeFragmentNew, so I haven’t included any of that code.

Problem: Button is deleting list items but it is deleting the first item in the list, not the item that is being selected.

Recipe.java

    public class Recipe {

    private UUID mID;
    private String mName;
    private Date mDate;
    private boolean mIsFavorite;

    private final ArrayList<Ingredient> ingredients;
    public final ArrayList<Instruction> instructions;


    public Recipe() {
        mID = UUID.randomUUID();
        mDate = new Date();
        this.ingredients = new ArrayList<>();
        this.instructions = new ArrayList<>();
    }

    public UUID getID() {
        return mID;
    }

    public String getName() {
        return mName;
    }

    public void setName(String name) {
        mName = name;
    }

    public Date getDate() {
        return mDate;
    }

    public void setDate(Date date) {
        mDate = date;
    }

    public boolean isFavorite() {
        return mIsFavorite;
    }

    public void setFavorite(boolean favorite) {
        mIsFavorite = favorite;
    }

    public ArrayList<Ingredient> getIngredients() {
        return ingredients;
    }

    public ArrayList<Instruction> getInstructions() {
        return instructions;
    }
}

Ingredient.java

    public class Ingredient {

    private String name;
    private String amount;


    public Ingredient(String name, String amount) {
        this.name = name;
        this.amount = amount;
    }

    public String getName() {
        return name;
    }

    public String getAmount() {
        return amount;
    }

    @Override
    public String toString() {
        return this.name + "  " + this.amount;
    }
}

The arrayList is retreived from Recipe class using mRecipe.getIngredients().

The ListView is mIngredientWindow.

RecipeFragmentNew.java

public class RecipeFragmentNew extends Fragment implements IngredientListDialog.OnInputSelected {


public static final String TAG = "RecipeFragmentNew";
public static final String DIALOG_INGREDIENTS = "DialogIngredients";

private Recipe mRecipe;
private EditText mNameField;
private Button mIngredientAdd;
private Button mIngredientDelete;
private ListView mIngredientWindow;


private int listViewPosition;


private ArrayAdapter<Ingredient> listAdapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    
    UUID recipeId = (UUID) getArguments().getSerializable(ARG_RECIPE_ID);
    mRecipe = RecipeQueue.get(getActivity()).getRecipe(recipeId);

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.lists_detail_view, container, false);



    mIngredientDelete = v.findViewById(R.id.delete_ingredient_button);

    
    mIngredientDelete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

               for (int i = 0; i < mRecipe.getIngredients().size(); i++) {
                if (i == listViewPosition) {
                   mRecipe.getIngredients().remove(i);

                }
                listAdapter.notifyDataSetChanged();
            }

        }
    });

  

    listAdapter = new ArrayAdapter<Ingredient>(
            getActivity(),
            android.R.layout.simple_list_item_1,
            mRecipe.getIngredients()
    );


    mIngredientWindow = v.findViewById(R.id.ingredients_window);
    mIngredientWindow.setAdapter(listAdapter);

    AdapterView.OnItemSelectedListener itemSelectedListener = new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            
              listViewPosition = position;

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    };

Answer

Button is deleting list items but it is deleting the first item in the list, not the item that is being selected.

The variable listViewPosition is always 0 because the setOnItemSelectedListener is not called. please check this answer So you can replace this method with setOnItemClicklistener like the below code:

mIngredientWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //mIngredientWindow.setSelection(position);
            listViewPosition = position;

        }
    });

Leave a Reply

Your email address will not be published. Required fields are marked *