Search code examples
androidsqliteandroid-sqlite

SQLite, Android : Can I bypass the call cursor.getColumnIndex(COLUMN_NAME) if I know the ColumnIndex?


I am a newbie in Android. For cursor handling I find a debate and that confuses me. Let us consider the call

public static final String COLUMN_NAME = "my_column_name";
cursor.getString(cursor.getColumnIndex(COLUMN_NAME));

Now I am reading a debate that cursor.getColumnIndex function is adding overhead to the cursor loop and therefore be called before the loop. (There is a counter argument that recent coding has placed a one time map ). Is this index implicitly created when I am creating the table and hence I am forced to call it? And if so, isn't it counterproductive ?

OR

This index is a map of column names only and the first column is 0, second column is 1 and so on and therefore if I know the create statement syntax for the table, I can easily identify the column index myself?

I would be very much pleased to be guided to further notes. Thanks in advance.


Solution

  • This index is a map of column names only and the first column is 0, second column is 1 and so on and therefore if I know the create statement syntax for the table, I can easily identify the column index myself?

    The answer to the above question is Yes.

    Well, you can pass the index directly to cursor.getString or any other respective methods but you should call cursor.getColumnIndex(COLUMN_NAME) just to be safe so that you are not giving the wrong index to the cursor. So you can do one thing, call the cursor.getColumnIndex(COLUMN_NAME) and store the index in a variable before the loop starts, and in the loop use that variable which holds the value of the index.

    Well my recommendation is to use room persistence library for sqlite, sooner or later you will fall in love with it.