Get boolean from database using Android and SQLite
When you need to retrieve a boolean from an SQLite database in Android, you need to remember that it is stored as an integer (0
or 1
). Use a Cursor
to fetch the integer and convert it into a boolean:
Here, myTable
and myBooleanColumn
are placeholders for your table and boolean column respectively. The query
function is called to fetch the column and getInt
is used to convert the first column of the cursor row into a boolean.
Fetching booleans stored as strings
If the booleans are stored as strings, use this piece of magic:
Here, equalsIgnoreCase
is used with caution to handle any case variations in the database values while storing booleans.
Choosing the right method for the job
It’s prime time to remember that SQLite doesn't natively support boolean types. Hence, we deal with booleans as either integers (0/1
) or strings ("false"/"true"
). So, you must match the method to the respective data type. Using getInt()
for integer representation and getString()
for string representation ensures smooth sailing in all circumstances.
Lay the golden rules for your booleans
Half the battle is won if you have a strategy for storing booleans. Here are some rules and recommendations to keep in mind:
Using integers to store booleans
- Consistency: It’s a binary world, stick with
0
or1
. - Retrieval: With the truth table in mind, use
cursor.getInt(boolean_column_index) == 1
.
Using strings to store booleans
- Consistency: Stick with the brotherhood of lowercase or the aristocracy of uppercase when storing.
- Retrieval: Drop
cursor.getString(boolean_column_index).equalsIgnoreCase("true")
into the magic hat and ... voilà!
Preventing conflicts
- Confusion: No mix and matching of
0
and"false"
,1
and"true"
. - Solution: Stick to one method, and if change is the only constant, then have a migration plan.
Was this article helpful?