从Android的SQLite数据库中删除 [英] Deleting from Android SQLite Database

查看:84
本文介绍了从Android的SQLite数据库中删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题

Question

我试图用一个按钮来删除第一个进入我的数据库。我以为我有code正确的,但它似乎并没有被删除任何数据,当删除按钮pssed的Andr​​oid $ P $的设置,使此,因为它的onClick 方法: -

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"/>

我使用的是内置的的onClick 去我想要的方式。我在应用程序的其他部分使用这个和它的作品就好了。

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:

这是公认的答案,我参加了该code和创造了DatabaseHelper类名调用删除第一。在code我用的是: -

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);
   }
}

然后我改变了code上面我给了:

and I then changed the code I gave above to:

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

fillData()方法刷新视图。

推荐答案

在数据库中的第一个记录不会总是具有0的ID。每次插入新记录的主键将自动加1递增所以,你需要的是得到的第一个记录的ID,并执行使用该ID的删除。

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);
   }

这篇关于从Android的SQLite数据库中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆