cesar
cesar

Reputation: 9074

Android SQLite: Is it a good practice to call getColumnIndex when retrieving values from a table?

Right now, I have my code looking like this:

SqlTables.java:

// Separate file
public enum SqlTables {
    TABLE_1("table_1"),
    .
    .
    .
    TABLE_N("table_n");
    final String name;
    private SqlTables(String name) {
        this.name = name;
    }
}

Table1Columns.java:

// Separate file
public enum Table1Columns {
    ...
}

SqlDatabaseInterface.java:

Cursor c = db.query(SqlTables.TABLE_1.toString(), null...);
final int indexId = c.getColumnIndexOrThrow(
        Table1Columns.ID.toString());
final int indexName = c.getColumnIndexOrThrow(
        Table1Columns.NAME.toString());
while (c.moveToNext()) {
    final String id = c.getString(indexId);
    final String name = c.getString(indexName);
}

I did not find any documentation regarding how Android mapped columns to indices, so while I've confirmed that it is based on the order in which the columns were stated in the query, I do not have a guarantee that this will work 100% of the time, or that future updates will keep this behavior. The benefits of using getColumnIndexOrThrow(...) is the guarantee that my indices will always be correct, so long as the columns they reference are included in the query. The downside is that, besides the tedium, it makes my code much harder to read and greatly increases the length of my methods. On the other hand, I could just specify the indices without calling getColumnsIndexOrThrow, and that'd shorten my code, but the lack of documentation makes it feel wrong.

Upvotes: 1

Views: 2088

Answers (1)

Alex Lockwood
Alex Lockwood

Reputation: 83301

No, you definitely should not hard code the column index values into your code. If you do, your database will be nearly impossible to manage (since making changes to the table could cause the index values to change).

From what I can tell, your code is difficult to read because:

  1. You are literring your code with unnecessary calls to toString(). Just get rid of them... they are completely redundant.

  2. You are using the final keyword way too much and its cluttering your code. This should be used as a precaution in situations where you might accidentally change the value of a variable. This is not one of those situations...

  3. You are spreading simple statements across multiple lines. Just use one line and it'll make it a lot easier to read.

That said, there is technically nothing wrong with any of the above coding practices. I'm just saying, if you really care about making your code easy to read then you might want to consider them as suggestions.

Upvotes: 3

Related Questions