2

I'm using the SQLite-asset-helper by jgilfelt

I try to look into his sample project and came across this code:

    public Cursor getEmployees() {

    SQLiteDatabase db = getReadableDatabase();
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

    String [] sqlSelect = {"0 _id", "FirstName", "LastName"}; 
    String sqlTables = "Employees";

    qb.setTables(sqlTables);
    Cursor c = qb.query(db, sqlSelect, null, null,
            null, null, null);

    c.moveToFirst();
    return c;

}

What's the meaning of "0" in that select statement for _ID field?

Jezer Crespo
  • 2,152
  • 3
  • 24
  • 27

2 Answers2

2

It is returning the value of 0 with the column name _id (it's using column name alias).

You can return a column that doesn't exist in your table this way.

Szymon
  • 42,577
  • 16
  • 96
  • 114
  • Yeah I noticed there is no column _id in the table.So if I print the value of _id, it would just return 0 all the time, right? – Jezer Crespo Jan 05 '14 at 11:11
  • 2
    As for **_id**, i'd use **rowid _id**, so it would return the REAL row id (which is a HIDDEN column in every SQLite table), instead of 0. – Phantômaxx Jan 05 '14 at 11:16
1

Some Android adapters require you to always have an _id field selected even if your table doesn't have one. Try it, your app will crash without selecting an _id. So they are doing a workaround for this by selecting a mock _id value that has 0 in it.

EDIT: A better way to do this would be for example if you want to use "id" instead of "_id" in your tables, just do a SELECT id as _id FROM ...

VM4
  • 6,321
  • 5
  • 37
  • 51
  • This is not true. I have just tried it, at least on 4.4 it works with returning a single column with any name, e.g. `{"2 aaa"}`. – Szymon Jan 05 '14 at 11:09
  • 1
    This depends on what adapter you are using. More here: http://stackoverflow.com/questions/3192064/about-id-field-in-android-sqlite – VM4 Jan 05 '14 at 11:10
  • The code in question has a link at the top, that code uses the Cursor in a SimpleCursorAdapter. – VM4 Jan 05 '14 at 11:13