dimanche 31 janvier 2016

Why is the cursor never null?

I am making an android app where I am storing some id's in a sqlite database. Depending upon user's action I'm either adding the id if not already added or removing the id if already added. But the problem is the cursor in my method getExhibitor(int id) is always returning true. I dont understand why. Can anybody help?

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

Aucun commentaire:

Enregistrer un commentaire