Jitesh Upadhyay
Jitesh Upadhyay

Reputation: 5260

Counting no of columns in an android sqlite table

Hi i wants to count the total number of columns in android sqlite table, please guide that how to achieve? what i tried is below

    public int numberOfColumns(String tableName) {


    Cursor cursor = database.query(tableName, null, null, null, null, null, null);

    if (cursor != null) {
        if (cursor.getColumnCount() > 0) {
            return cursor.getColumnCount();
        } else {
            return 0;
        }
    } else {
        return 0;
    }
}

this works fine, what i wants to know is about it is, this approach is fine or anything better i can do!! i visited lot of stackoverflow links but still have confusion.

Upvotes: 1

Views: 999

Answers (2)

Guillermo Merino
Guillermo Merino

Reputation: 3257

You need to close your cursor after leaving the function, this change should work (not tested)

public int numberOfColumns(String tableName) {
    int result = 0;
    Cursor cursor = null;
    try {
        cursor = database.query(tableName, null, null, null, null, null,
                null);
        result = cursor.getColumnCount();
        if (result < 0) {
            result = 0;
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return result;
}

Upvotes: 2

laalto
laalto

Reputation: 152817

This works. There are some other methods such as PRAGMA table_info(tablename) but they aren't really that much better.

Checking for cursor != null is not necessary.

Also, it's a good idea to close your cursor before exiting the method.

Upvotes: 2

Related Questions