Home » Android » How to Add a Boolean Column in Android SQlite

How to Add a Boolean Column in Android SQlite

Posted by: admin April 23, 2020 Leave a comment

Questions:

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”.

How to&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);

Answer:

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

Answer:

public enum Status{
        TRUE,FALSE;
}
static final String CREATE_DB_TABLE = 
  " CREATE TABLE " + CONTACTS_TABLE_NAME +
  " (_id INTEGER PRIMARY KEY AUTOINCREMENT, " +......
  " booleanColumn INTEGER DEFAULT 0);";

//while inserting

pass Status.TRUE.ordinal() values to database and

//while retrieving

cross check with the ordinal value for status

Answer:

Sqlite does not provide any class to store boolean values.

You can use 0 for false and 1 for true. You will then have to convert these values after retrieving them from your database.

Answer:

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