Does anyone know how to delete an item from a custom ListView? I'm currently working on an Android bar code scanner that stores a scanned item name into an inventory, together with its price. I also want it to be removed when the user clicks on it (but it doesn't works).
This is my code, which might seem messy because I'm still a beginner in Android.
XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="in.aurora.android_barcode_scanner.Inventory"
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false">
<ListView
android:id="@+id/listView"
android:layout_width="365dp"
android:layout_height="495dp"
tools:layout_editor_absoluteX="10dp"
tools:layout_editor_absoluteY="8dp"
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false"/>
</android.support.constraint.ConstraintLayout>
Implementation:
public void display() {
ShoppingListAdapter adapter = new ShoppingListAdapter(this,
R.layout.adapter_view_layout, shoppingList);
lv = (ListView) findViewById(R.id.listView);
lv.setAdapter(adapter);
}
@Override
public void onItemClick(AdapterView parent, View view, final int position, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Remove this item?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
shoppingList.remove(position);
display();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
Adapter:
public class ShoppingListAdapter extends ArrayAdapter<Product> {
private static final String TAG = "ShoppingListAdapter";
private Context mContext;
int mResource;
public ShoppingListAdapter(Context context, int resource, ArrayList<Product> objects)
{
super(context, resource, objects);
mContext = context;
mResource = resource;
}
@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
String name = getItem(position).getName();
double price = getItem(position).getPrice();
String convertPrice = Double.toString(price);
Product product = new Product(name, price);
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mResource, parent, false);
TextView productName = (TextView)
convertView.findViewById(R.id.textView1);
TextView productPrice = (TextView)
convertView.findViewById(R.id.textView2);
productName.setText(name);
productPrice.setText(convertPrice);
return convertView;
}
}