In ANDROID how delete data from LISTVIEW by Button click?

十年热恋 提交于 2020-01-07 05:39:05

问题


in my application Listview is populated with data from Sqlite database. i use button to delete the items. And also modify the table in Sqlite Db .
SQL DB Class

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_table);
    tv = (TextView) findViewById(R.id.txt_rates);
    //  checkout = (Button) findViewById(R.id.submit_btn);
    ListCart = (ListView) findViewById(R.id.list_item);
    pDialog = new ProgressDialog(this);
    ctx = this;
    CartData = Table.this.openOrCreateDatabase("SHOPPING_CART", MODE_PRIVATE, null);
    CartData.execSQL("CREATE TABLE IF NOT EXISTS cart_items(product_id varchar, name varchar, price varchar, quantity integer, model varchar, image varchar, manufacturer varchar )");
    ArrayList<CartProducts> myList = new ArrayList<CartProducts>();
    Cursor crsr = CartData.rawQuery("SELECT * FROM cart_items", null);
    final String[] productID = new String[crsr.getCount()];
    final String[] ProductName = new String[crsr.getCount()];
    final String[] ProductPrice = new String[crsr.getCount()];
    final String[] ProductQuantity = new String[crsr.getCount()];
    final String[] ProductModel = new String[crsr.getCount()];
    final String[] ProductImage = new String[crsr.getCount()];
    final String[] ProductManufacturer = new String[crsr.getCount()];
    int j = 0;

    while (crsr.moveToNext()) {
        String id = crsr.getString(crsr.getColumnIndex("product_id"));
        productID[j] = id;//product_id,name,price,quantity,model,image,manufacturer
        name = crsr.getString(crsr.getColumnIndex("name"));
        ProductName[j] = name;
        String price = crsr.getString(crsr.getColumnIndex("price"));
        ProductPrice[j] = price;
        String s = ProductPrice[j].toString();
        s = s.replace(",", "");
        String[] parts = s.split("\\."); // escape .
        String part1 = parts[0];
        String part2 = parts[1];
        part1 = part1.replace("₹", "");
        total = Integer.parseInt(part1); // Toast.makeText(Table.this, part1, Toast.LENGTH_SHORT).show();
        String qnty = crsr.getString(crsr.getColumnIndex("quantity"));
        ProductQuantity[j] = qnty;
        String s2 = ProductQuantity[j].toString();
        total1 = Integer.parseInt(s2);
        sum = total * total1;
        String model = crsr.getString(crsr.getColumnIndex("model"));
        ProductModel[j] = model;
        String image = crsr.getString(crsr.getColumnIndex("image"));
        ProductImage[j] = image;
        String manufacturer = crsr.getString(crsr.getColumnIndex("manufacturer"));
        ProductManufacturer[j] = manufacturer;
        //Toast.makeText(getApplicationContext(),productID[j]+""+ProductName[j]+""+ProductPrice[j]+""+ProductQuantity[j]+""+ProductModel[j]+""+ProductImage[j]+""+ProductManufacturer[j] , Toast.LENGTH_SHORT).show();
        myList.add(new CartProducts(productID[j], ProductName[j], ProductPrice[j], ProductQuantity[j], ProductModel[j], ProductImage[j], ProductManufacturer[j]));
        j++;
        gtot = gtot + sum;
    }
    ListCart.setAdapter(new CartProduct_ListAdapter(ctx, R.layout.activity_cart_row, myList));
    tv.setText("Rs. " + String.valueOf(gtot));
    String s1 = ProductPrice.toString();
    /*Delete Query*/

    /* db.execSQL("DELETE FROM cart_items WHERE product_id='"+editRollno.getText()+"'"); */

  /*  checkout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(getApplicationContext(), Product_details.class);
            startActivity(i);
        }
    }); */
}


Adapter class

public class CartProduct_ListAdapter extends ArrayAdapter<CartProducts> {
Bitmap bitmap;
ImageView img;
String urll;
SQLiteDatabase CartData;
SQLiteOpenHelper dbhelper;
Integer total = 0, quanty = 1, grandtot = 0, fulltotal = 0, i = 0, sum;
int it;
private int resource;
private LayoutInflater inflater;
private Context context;

public CartProduct_ListAdapter(Context ctx, int resourceId, List<CartProducts> objects) {

    super(ctx, resourceId, objects);
    resource = resourceId;
    inflater = LayoutInflater.from(ctx);
    context = ctx;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    /* create a new view of my layout and inflate it in the row */
    convertView = (RelativeLayout) inflater.inflate(resource, null);
    final CartProducts banqt = getItem(position);
    TextView txtprice = (TextView) convertView.findViewById(R.id.txt_item_price);
    txtprice.setText(banqt.getPrice());
    String s = txtprice.getText().toString();
    s = s.replace(",", "");
    String[] parts = s.split("\\."); // escape .
    String part1 = parts[0];
    String part2 = parts[1];
    part1 = part1.replace("₹", "");// Toast.makeText(getContext(), part1, Toast.LENGTH_LONG).show();
    total = Integer.parseInt(part1);
    EditText editqu = (EditText) convertView.findViewById(R.id.edt_qn);
    editqu.setText(banqt.getQuantity());
    quanty = Integer.parseInt(editqu.getText().toString());
    grandtot = total * quanty;
    TextView total = (TextView) convertView.findViewById(R.id.txt_total);
    total.setText(String.valueOf(grandtot));
    Button delet = (Button) convertView.findViewById(R.id.btn_remove);
    delet.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            /*delete function*/
            it = Integer.parseInt(banqt.getProduct_id());
            Log.e("***i value******", String.valueOf(it)); //Toast.makeText(getContext(), String.valueOf(it), Toast.LENGTH_LONG).show();
            CartData.delete("cart_items", "product_id='" + it + "'", null);
            CartData.close();
        }
    });
    TextView txtName = (TextView) convertView.findViewById(R.id.product_name);
    txtName.setText(banqt.getName());

    img = (ImageView) convertView.findViewById(R.id.img_product);
    urll = banqt.getImage().toString();

    urll = urll.replaceAll(" ", "%20");// Toast.makeText(getContext(),urll,Toast.LENGTH_LONG).show();
    new LoadImage().execute(urll);
    return convertView;

}

private class LoadImage extends AsyncTask<String, String, Bitmap> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    protected Bitmap doInBackground(String... args) {
        try {
            bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    protected void onPostExecute(Bitmap image) {
        if (image != null) {
            img.setImageBitmap(image);
            //    pDialog.dismiss();
        } else {
            //  pDialog.dismiss();
            Toast.makeText(getContext(), "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
        }
    }
 }
   }


And layout im using CardView And im inflate CardView on my layout
XML CardView code

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="290dp"
    android:id="@+id/cv"
    android:layout_marginTop="10dp"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    card_view:cardCornerRadius="0dp"
    card_view:cardBackgroundColor="#FFFFFF">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/r1">
        <ImageView
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:id="@+id/img_product"
            android:layout_centerHorizontal="true" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/product_name"
            android:layout_below="@id/img_product"
            android:textSize="18dp"
            android:text="Parvana Fancy Necklace Set"
            android:layout_marginTop="25dp"
            android:textStyle="bold"
            android:inputType="textMultiLine"
            android:layout_centerHorizontal="true" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/txt_item_price"
            android:text="12000 INR"
            android:textStyle="bold"
            android:textSize="15dp"
            android:gravity="center"
            android:layout_alignTop="@+id/edt_qn"
            android:layout_below="@id/product_name"
            android:layout_marginLeft="25dp"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/txt_availability"
            android:text="x"
            android:textStyle="bold"
            android:textSize="16dp"
            android:layout_alignTop="@+id/txt_item_price"
            android:layout_toRightOf="@+id/txt_item_price"
            android:layout_toEndOf="@+id/txt_item_price"
            android:layout_marginLeft="10dp"
            android:layout_marginStart="54dp" />
        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/edt_qn"
            android:textSize="16dp"
            android:layout_toRightOf="@id/txt_availability"
            android:layout_below="@id/product_name"
            android:layout_marginTop="18dp"
            android:layout_marginLeft="10dp"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/txt_eql"
            android:text="="
            android:layout_toRightOf="@id/edt_qn"
            android:layout_below="@id/product_name"
            android:layout_marginTop="22dp"
            android:layout_marginLeft="10dp"
            android:textStyle="bold"
            android:textSize="16dp"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/txt_total"
            android:text="RS.234"
            android:layout_toRightOf="@id/txt_eql"
            android:layout_below="@id/product_name"
            android:layout_marginTop="25dp"
            android:layout_marginLeft="10dp"
            android:textStyle="bold"
            android:textSize="15dp"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btn_remove"
            android:text="  Delete"
            android:textSize="13dp"
            android:drawableLeft="@drawable/delete_icon"
            android:layout_alignParentBottom="true"
            android:layout_alignLeft="@+id/txt_availability"
            android:layout_alignStart="@+id/txt_availability" />
    </RelativeLayout>
</android.support.v7.widget.CardView>


回答1:


this is what i have done to delete list row try something like this in your adapter class

delet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
            cartdata.updateSelected(Integer.parseInt(cart_pdiscription[i]), 0);
            cartdata.deleteProduct(Integer.parseInt(cart_pdiscription[i]));                
            Intent intent = ((CartList) context).getIntent();
            ((CartList) context).finish();
            context.startActivity(intent);

        }
    });


来源:https://stackoverflow.com/questions/32919600/in-android-how-delete-data-from-listview-by-button-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!