Deleting from Android SQLite Database

北城余情 提交于 2019-12-11 11:56:18

问题


Question


I am trying to use a button to delete the first entry to my database. I thought I had the code right but it does not seem to be deleting any of the data, when the delete button is pressed android is setup so which this as it onClick method:-

public void delete(View view)
 {
     datasource.open();
     datasource.deleteTitle(0);
     datasource.close();
 }

the delete method it is calling is this method here:-

 public boolean deleteTitle(long rowId) 
{
    return db.delete(DATABASE_TABLE, KEY_ROWID + 
            "=" + rowId, null) > 0;
}

is there a different way I should be doing this?

The button is set up like this :-

   <Button
        android:id="@+id/delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Delete First" 
        android:onClick="delete"/>

I am using the built in onClick to go to the method I want. I am using this in other parts of the application and it works just fine.

Solution:


From the accepted answer, I took the code in that and created a call in the DatabaseHelper class names delete first. The code I used was :-

public void deleteFirst()
{
    Cursor cursor = db.query(DATABASE_TABLE, null, null, null, null, null, null); 

    if(cursor.moveToFirst()) {
        long rowId = cursor.getLong(cursor.getColumnIndex(KEY_ROWID)); 

        db.delete(DATABASE_TABLE, KEY_ROWID +  "=" + rowId, null);
   }
}

and I then changed the code I gave above to:

public void delete(View view)
 {
     datasource.open();
     datasource.deleteFirst();
     fillData();
     datasource.close();
 }

with the fillData() method refreshing the view.


回答1:


The first record in the database will not always have an ID of "0". Each time you insert a new record the primary key will increment by 1. So what you need is to get the id of the first record, and perform the delete using that id.

Cursor cursor = db.query(DATABASE_TABLE, null, null, null, null, null, null); 

    if(cursor.moveToFirst()) {
        long rowId = cursor.getLong(cursor.getColumnIndex(KEY_ROWID)); 

        db.delete(DATABASE_TABLE, KEY_ROWID +  "=" + rowId, null);
   }



回答2:


stop worrieng about sql and use greenDAO :) very simple, super easy and lightweight sqllite framework for android

http://greendao-orm.com/



来源:https://stackoverflow.com/questions/9997553/deleting-from-android-sqlite-database

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