Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Add a Boolean Column in Android SQlite

I have created a table for my ContentProvider using the following line :

static final String CREATE_DB_TABLE = 
  " CREATE TABLE " + CONTACTS_TABLE_NAME +
  " (_id INTEGER PRIMARY KEY AUTOINCREMENT, " + 
  " pid TEXT NOT NULL, " +
  " name TEXT NOT NULL,"+
  "number TEXT NOT NULL);";

It has 4 columns. Now i want to add a column with a boolean value of true/false. How can i add append/change this statement if i have to add a boolean column named "status".

like image 945
BST Kaal Avatar asked Jul 07 '14 07:07

BST Kaal


People also ask

How do I add a Boolean in SQLite?

Basically, SQLite does not support the Boolean data type, so instead of Boolean type SQLite uses the integer data type to execute the Boolean expression in the form of true or false here 0 is used for false and 1 for true that we already discussed.

Can you store Boolean in SQLite?

SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as integers 0 (false) and 1 (true). SQLite recognizes the keywords "TRUE" and "FALSE", as of version 3.23. 0 (2018-04-02) but those keywords are really just alternative spellings for the integer literals 1 and 0 respectively.

How do you store a Boolean?

Instead, Boolean values are stored as integers 0 (false) and 1 (true). You can convert boolean to int in this way: int flag = (boolValue)?

Does SQLite support a BLOB type?

(10) Does SQLite support a BLOB type? SQLite allows you to store BLOB data in any column, even columns that are declared to hold some other type. BLOBs can even be used as PRIMARY KEYs.


3 Answers

You could use something like this:

Create your table:

static final String CREATE_DB_TABLE = 
    "CREATE TABLE " + CONTACTS_TABLE_NAME " + 
    " (_id INTEGER PRIMARY KEY AUTOINCREMENT," + 
    "..." + " flag INTEGER DEFAULT 0)";

retrieve your value as:

Boolean flag = (cursor.getInt(cursor.getColumnIndex("flag")) == 1);
like image 137
Phantômaxx Avatar answered Oct 07 '22 06:10

Phantômaxx


As mentioned by M D,

SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as integers 0 (false) and 1 (true).

Use the following ALTER statement -

ALTER TABLE CREATE_DB_TABLE ADD status boolean NOT NULL default 0;

Then you can use Cursor to get the required value and then convert to actual boolean -

flag=cursor.getString(0).equals("1")

You can use this flag to display on user screen.

Reference: http://www.sqlite.org/datatype3.html

like image 20
My God Avatar answered Oct 07 '22 05:10

My God


unfortunately android sqlite does not support Boolean type and you should use Integer instead of it

like image 26
Abolfazl Miadian Avatar answered Oct 07 '22 07:10

Abolfazl Miadian