从listview中删除项目(使用sqlite删除查询)

时间:2013-05-08 06:50:44

标签: android

我想通过ItemlongClickListener从listview中删除项目。显示项是我的数据库的列值。数据库查询是在单独的文件中编写的,listview代码是在单独的文件中。 我试过但我的应用程序停止了.. 我的ListView页面代码如下:

fav_quote.setOnItemLongClickListener(new OnItemLongClickListener() {
        public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
            Log.w("DELETED", " DELETED");

            String position1 =  adapt.getItem(position);

           Fav del = new Fav(this);
           del.deleteEntry(position1);
           del.close();
          return false;              
        }

数据库代码

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXIST " + DATABASE_TABLE);
        onCreate(db);
    }       
}

public Fav(Context c) {

    ourContext = c;
}

public Fav(OnItemLongClickListener onItemLongClickListener) {
    Context c1 = null;
    ourContext = c1;
    // TODO Auto-generated constructor stub
}

public Fav open() throws SQLException {
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this; 
}
public void close (){

    ourHelper.close();
}

public long createEntry(String header, String quote_value) {
    // TODO Auto-generated method stub
    ContentValues cv = new ContentValues();
    cv.put(KEY_HEADER, header);
    cv.put(KEY_QUOTE_VALUE, quote_value);
    return ourDatabase.insert(DATABASE_TABLE, null, cv);
}

public String getData() {
    // TODO Auto-generated method stub
    String[] columns = new String []{KEY_ROWID, KEY_HEADER, KEY_QUOTE_VALUE};       

    Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
    String result = "";     
    int iRow = c.getColumnIndex(KEY_ROWID);
    int iHeader = c.getColumnIndex(KEY_HEADER);
    int iQuote_value = c.getColumnIndex(KEY_QUOTE_VALUE);

    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
        result = result + c.getString(iRow)+ "." +c.getString(iHeader)+ ":" +c.getString(iQuote_value)+ ":";
    }       
    return result;              
}

public void deleteEntry(String position1) {
    // TODO Auto-generated method stub
    ourDatabase.delete(DATABASE_TABLE, KEY_ROWID + "=" + position1 , null);
}

3 个答案:

答案 0 :(得分:1)

是否从数据库中删除了值? 如果是,则从适配器调用方法中删除该条目

    notifyDataSetChanged();

如果没有数据库的问题。

答案 1 :(得分:0)

在deleteEntry类中,你必须初始化sqlite,如。

public void deleteEntry(String position1) {
// TODO Auto-generated method stub
 SQLiteDatabase ourDatabase = this.getWritableDatabase();
ourDatabase.delete(DATABASE_TABLE, KEY_ROWID + "=" + position1 , null);
}

答案 2 :(得分:0)

尝试

Fav del = new Fav(NameOfActivityClass.this);