jeudi 14 mai 2015

Deleting items in ListView using intent

my problem is that im trying to delete items from ListView and for that I have a button in CustomAdapter.

Im setting this button an onClickListener and try to pass item name to main activity using Intent.

In Main when intent named "deleteProduct" is received the method deleteProduct is called and in this method im trying to pass to database a product name which to delete.

my CustomAdapter:

 final Product singleProduct=getItem(position);


final Button DeleteButton = (Button)customView.findViewById(R.id.DeleteButton);
  DeleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(v.getContext(),MainActivity.class);
                i.putExtra("deletProduct","deleteProduct");
                i.putExtra("productname",singleProduct.get_productname());
                v.getContext().startActivity(i);
            }
        });

MY Main:

 @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent.getStringExtra("deleteProduct").equals("deleteProcust")) {
            deleteProduct();
        }
    }
 private void deleteProduct(){
            Bundle productData=getIntent().getExtras();
        if(productData==null) return;

        String productname=productData.getString("productname");
        dbhandler.deleteProduct(productname);
        getProductsFromDb();
    }

And my DBHandler:

 public void deleteProduct(String productname){
        SQLiteDatabase db=getWritableDatabase();
        db.execSQL("DELETE FROM" +TABLE_PRODUCTS+ "WHERE "+ COLUMN_PRODUCTNAME+ "=\""+ productname +"\";");
        }

    public ArrayList<Product> getProducts(){
        ArrayList<Product> products= new ArrayList<>();
        SQLiteDatabase db=getWritableDatabase();
        String query= "SELECT * FROM "+ TABLE_PRODUCTS +";";

        Cursor c= db.rawQuery(query,null);
        c.moveToFirst();
        while (!c.isAfterLast()){
            if(c.getString(c.getColumnIndex("productname"))!=null){
                Product product=new Product(Integer.parseInt(c.getString(c.getColumnIndex(COLUMN_ID))),c.getString(c.getColumnIndex(COLUMN_PRODUCTNAME)),Boolean.valueOf(c.getString(c.getColumnIndex(COLUMN_ISCHECKED))));
                products.add(product);
            }
            c.moveToNext();
        }
        db.close();
        return products;
    }

Also im getting this message in logcat when i click delete button:

1845-1845/com.example.olev.shoppinglist W/ViewRootImpl﹕ Dropping event due to no window focus: KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_ALT_RIGHT, scanCode=100, metaState=META_ALT_ON|META_ALT_RIGHT_ON, flags=0x8, repeatCount=16931, eventTime=1428851, downTime=560900, deviceId=1, source=0x301 }

Aucun commentaire:

Enregistrer un commentaire