我正在制作一个Android应用,在其中将一些ID存储在sqlite数据库中。根据用户的操作,我要么添加ID(如果尚未添加),要么删除ID(如果已添加)。但是问题是我的方法getExhibitor(int id)中的游标始终返回true。我不明白为什么。有人可以帮忙吗?
public class Interests extends SQLiteOpenHelper {
private Context context;
private static final int DATABASE_VERSION=1;
private static final String DATABASE_NAME="userInterests";
private static final String TABLE_EXHIBITORS="exhibitors";
// Column Names //
private static final String KEY_ID="id";
public Interests(Context context) {
super(context,DATABASE_NAME,null,DATABASE_VERSION);
this.context=context;
}
@Override
public void onCreate(SQLiteDatabase db) {
final String createQuery="CREATE TABLE IF NOT EXISTS "+TABLE_EXHIBITORS+"( "
+KEY_ID+" INTEGER PRIMARY KEY)";
db.execSQL(createQuery);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS"+TABLE_EXHIBITORS);
onCreate(db);
}
public void addExhibitor(int id){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(KEY_ID,id);
db.insert(TABLE_EXHIBITORS,null,values);
db.close();
Toast.makeText(context,"Exhibitor added",Toast.LENGTH_SHORT).show();
}
//This method is faulty//
public boolean getExhibitor(int id){
SQLiteDatabase db=this.getReadableDatabase();
Cursor c=db.query(TABLE_EXHIBITORS,new String[]{KEY_ID},KEY_ID+" = ? ",new String[]{String.valueOf(id)},null,null,null);
c.close();
return (c!=null); //Always true
}
public void removeExhibitor(int id){
SQLiteDatabase db=this.getWritableDatabase();
db.delete(TABLE_EXHIBITORS,KEY_ID+" = ?",new String[]{String.valueOf(id)});
Toast.makeText(context,"Exhibitor removed",Toast.LENGTH_SHORT).show();
db.close();
}
}
您应该检查游标的内容。
您总是会得到查询的结果行,它们可能为空,但不能为null。
尽管游标null
自您执行有效查询后就不会出现,但它可能会有一个getCount() == 0
或1
,这取决于它是否在数据库中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句