Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - BaseColumns and _id

I was reading this thread: What is the use of BaseColumns in Android, and I get how to use BaseColumns, that you have to fetch _id in your SELECT statements.

What's still unclear to me is when is the _id field "internally" created? Is it during execSQL(...) that Android adds the _id field? Or, do we still have to define it in the CREATE TABLE statement?

like image 979
ShrimpCrackers Avatar asked Feb 17 '23 15:02

ShrimpCrackers


1 Answers

You must create it "manually". Android won't do that for you.

For example, during table creation, you issue:

CREATE TABLE messages (_id INTEGER PRIMARY KEY AUTOINCREMENT, timestamp INTEGER, message TEXT);

See? The _id column is explicitly named and added.

Or, following the convention of DB-helper classes you'll come up with something like that:

db.execSQL("CREATE TABLE " + TABLE_MESSAGES + " ("
        + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
        + COLUMN_TIMESTAMP + " INTEGER,"
        + COLUMN_MESSAGE + " TEXT"
        + ");");

where the TABLE_* and COLUMN_* are constant fields of DB-helper, e.g.:

public static final String TABLE_MESSAGES = "messages";
public static final String COLUMN_TIMESTAMP = "timestamp";
public static final String COLUMN_MESSAGE = "message";
like image 172
andr Avatar answered Feb 27 '23 09:02

andr