简体   繁体   中英

Delete a row from sqlite using listview

Here i am creating three column on sqlite database on Databasehandler.java file then i am fetching data from database inside Cart.java file to display data into list view from fetching sqlite database it is working. My question is when i am pressing long click or click delete button it will be delete from list its not working you please help me.

my cart.java code

public class Cart extends Activity {

    private DatabaseHandlers mHelper;
    private SQLiteDatabase dataBase;

    private ArrayList<String> id = new ArrayList<String>();
    private ArrayList<String> hotelnonveg = new ArrayList<String>();
    private ArrayList<String> hotelcost = new ArrayList<String>();
    private ArrayList<String> hotelnewVal = new ArrayList<String>();


    private ListView userList;
    private AlertDialog.Builder build;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cart);

        userList = (ListView) findViewById(R.id.List);

        mHelper = new DatabaseHandlers(this);


            //click to update data
            userList.setOnItemClickListener(new OnItemClickListener() {

                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

                    Intent i = new Intent(getApplicationContext(),AddActivity.class);
                    i.putExtra("hotelnonveg", hotelnonveg.get(arg2));
                    i.putExtra("hotelcost", hotelcost.get(arg2));
                    i.putExtra("hotelnewVal", hotelnewVal.get(arg2));
                    i.putExtra("id", id.get(arg2));
                    i.putExtra("update", true);
                    startActivity(i);

                }
            });

            //long click to delete data
            userList.setOnItemLongClickListener(new OnItemLongClickListener() {

                public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                        final int arg2, long arg3) {

                    build = new AlertDialog.Builder(Cart.this);
                    build.setTitle("Delete " + hotelnonveg.get(arg2) + " "
                            + hotelcost.get(arg2));
                    build.setMessage("Do you want to delete ?");
                    build.setPositiveButton("Yes",
                            new DialogInterface.OnClickListener() {

                                public void onClick(DialogInterface dialog,
                                        int which) {

                                    Toast.makeText(
                                            getApplicationContext(),
                                            hotelnonveg.get(arg2) + " "
                                                    + hotelcost.get(arg2)
                                                    + " is deleted.", 3000).show();

                                    dataBase.delete(
                                            DatabaseHandlers.TABLE_CONTACTS,
                                            DatabaseHandlers.KEY_ID + "="
                                                    + id.get(arg2), null);
                                    displayData();
                                    dialog.cancel();
                                }
                            });

                    build.setNegativeButton("No",
                            new DialogInterface.OnClickListener() {

                                public void onClick(DialogInterface dialog,
                                        int which) {
                                    dialog.cancel();
                                }
                            });
                    AlertDialog alert = build.create();
                    alert.show();

                    return true;
                }
            });
        }


    @Override
    protected void onResume() {
        displayData();
        super.onResume();
    }

    /**
     * displays data from SQLite
     */



private void displayData() {
    dataBase = mHelper.getWritableDatabase();
    Cursor mCursor = dataBase.rawQuery("SELECT * FROM " + DatabaseHandlers.TABLE_CONTACTS, null);

    id.clear();
    hotelnonveg.clear();
    hotelcost.clear();
    hotelnewVal.clear();
    if (mCursor.moveToFirst()) {
        do {
            id.add(mCursor.getString(mCursor.getColumnIndex(DatabaseHandlers.KEY_ID)));
            hotelnonveg.add(mCursor.getString(mCursor.getColumnIndex(DatabaseHandlers.KEY_HOTELNONVEG)));
            hotelcost.add(mCursor.getString(mCursor.getColumnIndex(DatabaseHandlers.KEY_HOTELCOST)));
            hotelnewVal.add(mCursor.getString(mCursor.getColumnIndex(DatabaseHandlers.KEY_HOTELNEWVAL)));

        } while (mCursor.moveToNext());
    }
    DisplayAdapter disadpt = new DisplayAdapter(Cart.this,id, hotelnonveg, hotelcost, hotelnewVal);
    userList.setAdapter(disadpt);
    mCursor.close();
}

}

DisplayAdapter.java

  public class DisplayAdapter extends BaseAdapter {
            private Context mContext;
            private ArrayList<String> id;
            private ArrayList<String> hotelnonveg;
            private ArrayList<String> hotelcost;
            private ArrayList<String> hotelnewVal;
            private SQLiteDatabase dataBase;
            DatabaseHandlers mOpenHelper;
            static ArrayList<String> button;

            public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> hotelnonveg, ArrayList<String> hotelcost, ArrayList<String> hotelnewVal) {
                this.mContext = c;

                this.id = id;
                this.hotelnonveg = hotelnonveg;
                this.hotelcost = hotelcost;
                this.hotelnewVal = hotelnewVal;
                //this.button = button;
            }

            public int getCount() {
                // TODO Auto-generated method stub
                return id.size();
            }

            public Object getItem(int position) {
                // TODO Auto-generated method stub
                return null;
            }

            public long getItemId(int position) {
                // TODO Auto-generated method stub
                return 0;
            }

            public View getView(int pos, View child, ViewGroup parent) {
                final Holder mHolder;
                LayoutInflater layoutInflater;
                if (child == null) {
                    layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    child = layoutInflater.inflate(R.layout.listcell, null);
                    mHolder = new Holder();
                    mHolder.id = (TextView) child.findViewById(R.id.t_id);
                    mHolder.button = (Button) child.findViewById(R.id.button);          
                    mHolder.hotelnonveg = (TextView) child.findViewById(R.id.t_hotelnonveg);            
                    mHolder.hotelcost = (TextView) child.findViewById(R.id.t_hotelcost);
                    mHolder.hotelnewVal = (TextView) child.findViewById(R.id.t_hotelnewVal);
                    child.setTag(mHolder);




                } else {
                    mHolder = (Holder) child.getTag();
                }
                mHolder.id.setText(id.get(pos));
                mHolder.hotelnonveg.setText(hotelnonveg.get(pos));
                mHolder.hotelcost.setText(hotelcost.get(pos));
                mHolder.hotelnewVal.setText(hotelnewVal.get(pos));
                //mHolder.button.setButton(button.get(pos));
                mHolder.button.setText("Delete");


                return child;
            }

            public class Holder {
                TextView id;
                Button button;
                TextView hotelnonveg;
                TextView hotelcost;
                TextView hotelnewVal;
            }

        }

DatabaseHandlers.java

public class DatabaseHandlers extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;

private static final String DATABASE_NAME = "Cart";

static final String TABLE_CONTACTS = "cart";

static final String KEY_ID = "id";
static final String KEY_HOTELNONVEG = "hotelnonveg";
static final String KEY_HOTELCOST = "hotelcost";
static final String KEY_HOTELNEWVAL = "hotelnewVal";


public DatabaseHandlers(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_HOTELNONVEG + " TEXT,"
            + KEY_HOTELCOST + " TEXT," + KEY_HOTELNEWVAL + " TEXT)";
    db.execSQL(CREATE_CONTACTS_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

    onCreate(db);
}

void addGSorder(GSorder contact) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_HOTELNONVEG, contact.getHotelnonveg());
    values.put(KEY_HOTELCOST, contact.getHotelcost());
    values.put(KEY_HOTELNEWVAL, contact.getHotelnewVal());


    db.insert(TABLE_CONTACTS, null, values);
    db.close();
}

@SuppressWarnings("unused")
private Context getApplicationContext() {

    return null;
}


GSorder getGSorder(int id) {
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
            KEY_HOTELNONVEG,KEY_HOTELCOST,KEY_HOTELNEWVAL}, KEY_ID + "=?",
            new String[] { String.valueOf(id) }, null, null, null, null);
    if (cursor != null)
        cursor.moveToFirst();

    GSorder contact = new GSorder(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2),cursor.getString(3));
    return contact;
}

public ArrayList<GSorder> getAllGSorder() {
    ArrayList<GSorder> contactList = new ArrayList<GSorder>();

    String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    if (cursor.moveToFirst()) {
        do {
            GSorder contact = new GSorder();
            contact.setID(Integer.parseInt(cursor.getString(0)));
            contact.setHotelnonveg(cursor.getString(1));
            contact.setHotelcost(cursor.getString(2));
            contact.setHotelnewVal(cursor.getString(3));    

            contactList.add(contact);
        } while (cursor.moveToNext());
    }

    return contactList;
}

public int updateGSorder(GSorder contact) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_HOTELNONVEG, contact.getHotelnonveg());
    values.put(KEY_HOTELCOST, contact.getHotelcost());
    values.put(KEY_HOTELNEWVAL, contact.getHotelnewVal());


    return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
            new String[] { String.valueOf(contact.getID()) });
}

public void deleteGSorder(GSorder contact) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_CONTACTS, null, null);
    db.close();
}

public int getGSorderCount() {
    String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    cursor.close();
    return cursor.getCount();
}   

}

Instead of having an ArrayList for each property in your databasetable, you should make a model object, for example Contact which contains all the fields you want Like so

public class Contact {
   int id;
   String hotelCost;

}

etc ...

and then you can make your database retrieval code return an ArrayList<Contact> , and when you delete the row from database you should pass the row id not the name of the contact

So this

dataBase.delete(
    DatabaseHandlers.TABLE_CONTACTS,
    DatabaseHandlers.KEY_ID + "="
    + id.get(arg2), null);

needs to be changed to

dataBase.delete(
     DatabaseHandlers.TABLE_CONTACTS,
     DatabaseHandlers.KEY_ID + "="
     + contacts.get(position).getId(), null);

where contacts will be your ArrayList<Contact>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM