mercredi 14 octobre 2015

SQLite Database _id Integer Issue

I'm creating a simple SQLite Database in a DatabaseHelper class, which extends SQLiteOpenHelper. The database contains two columns, NAME and DESCRIPTION. Here is the method that runs in my onCreate Method within the DatabaseHelper class

     @Override
     public void onCreate(SQLiteDatabase db) {
         updateMyDatabase(db, 0, DATABASE_VERSION);
      }

    private void updateMyDatabase(SQLiteDatabase db, int olderVersion, int newerVersion){
    if (olderVersion<1){
        db.execSQL("CREATE TABLE MARK (_id INTEGER PRIMARY KEY AUTOINCREMENT,"
                + "NAME TEXT, "
                + "DESCRIPTION TEXT);");
        insertDrink(db,"latte","Espresso and Steamed Milk");
        insertDrink(db, "cappuccino", "This a Cappuccino");
    }
}


     private static void insertDrink(SQLiteDatabase database, String name, String description){
         ContentValues drinkValues = new ContentValues();
         drinkValues.put("NAME", name);
         drinkValues.put("DESCRIPTION",description);
         database.insert("MARK",null,drinkValues);
}

My specific question is regarding the _id INTEGER PRIMARY KEY used when the database is created. Does this number start at 1 or 0?

Here's why I'm wondering. I have a simple ListView with two items. I click the first item and pass the ListView's position, which is 0, to a different activity.

 listView.setOnItemClickListener(new ListView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch(position){
                case 0:{
                    Intent i = new Intent(MainActivity.this, Details.class);
                    i.putExtra(Details.EXTRA_DRINKNUM,(int)id);
                    startActivity(i);
                    break;
                }
                case 1:{
                    Intent i = new Intent(MainActivity.this, Details.class);
                    i.putExtra(Details.EXTRA_DRINKNUM,(int)id);
                    startActivity(i);
                    break;
                }
            }
        }
    });

I then retrieve this number within that Activity and place it in a variable called clickNum.

I then use clickNum to query the database:

        SQLiteOpenHelper database = new DatabaseHelper(this);
        SQLiteDatabase db = database.getReadableDatabase();
        Cursor cursor = db.query("MARK",
                new String[]{"NAME","DESCRIPTION"},
                "_id = ?",
                new String[]{Integer.toString(clickNum)},
                null,null,null);

I can ONLY pull up my first row containing the of data (Latte ....) if I do drinkNum + 1. Why is that? Shouldn't the first row _id be 0???

Thank you

Aucun commentaire:

Enregistrer un commentaire