I've result of a select query in a cursor object. I've some Boolean columns in the table. The value for Boolean type in SQLite is 0 or 1 depending on if they are false or true respectively. There are columns of int type too which can have value as 0 or 1 or other integer value. I want to return the value of a column from the cursor as,
if column is of boolean type
return true if value = 1
return false if value = 0
else
return the same value
How can I accomplish this?
How to determine if a column is boolean from cursor object?
So at first, SQLite does not have booleans type only integer, string, float, blob. So my suggestion is simply test value for int column and based on result perform appropriate action.
Cursor c = db.rawQuery(query, whereArgs);
int value = 0;
String[] intColumnNames = {columns};
int index = 0;
if (c.moveToFirst()) {
while (index < intColumnNames.length) {
do {
value = c.getInt(c.getColumnIndex(intColumnNames[index]));
switch (value) {
case 0:
// do some action
break;
case 1:
// do some action
break;
default:
// do some action for other cases
break;
}
} while(c.moveToNext());
index++;
}
}
As I have not faced similar problem before So I cannot post a gurranteed answer. but your question seems really interesting and after searching a bit I think one solution might be an option..
at first step before reading data determing the datatype of the column. For this the following links may be helpful
https://stackoverflow.com/a/6298521/931982
https://stackoverflow.com/a/3106349/931982
Then if you find that the column type is boolean then follow any of the solution provided by other two member.
N.B. it is not a confirmed answer, just posted my thinking. I would have commented this but it is too large to write in comment :(
While its true that SQLite doesn't have a BOOLEAN storage type, there's nothing to stop you defining a column with BOOLEAN as a data type. It will be stored as NUMERIC. Your application can use PRAGMA table_info( to get the data type and only do your true/false check if it is BOOLEAN.
try this
int columnNumber = 11;
while (cursor.moveToNext()) {
if( cursor.getInt(columnNumber) > 0){
//true
}
}
As there is no Boolean Data type in sqlite to use boolean you need to have data type INTEGER
SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as integers 0 (false) and 1 (true).
More Details
Related
I'm using Sugar ORM to query a list of apps. I have a boolean column for tagging fields in this using:
#Setter #Getter public boolean isNew = false;
Now after API call I will update and save the record to tag all new apps and then for display I will just query it using:
List<AppsModel> app_list = AppsModel.find(AppsModel.class, "is_new = ?", "true");
Problem is that it returns 0 entry where it to have 3 on my end. To check I get all the list and check the column one by one to check its values:
List<AppsModel> test = AppsModel.listAll(AppsModel.class);
for(int i=0;i<test.size();i++){
Log.e("Test app size", String.valueOf(test.get(i).isNew()));
}
And it returns 3 as expected with true values. I can make use of this loop for list but I don't want to as I want to keep my code clean as possible.
Am I missing something here?
Okay I found the answer here from satyan himself
So basically, using "true" will match it as String. So instead use:
List<AppsModel> app_list = AppsModel.find(AppsModel.class, "is_new = ?", "1");
As SQlite store boolean values as 0 and 1.
I have a database in my app with several columns of which 3 are: _id name selected.
Now, I want to read a single selected value from a row with the name being a string I get from some code. What would be the best way to do this?
Thanks
P.S. I am getting that value to check if it's 0 or 1 (only two possible values), so I want to ask how to make a kind of an if statement in the return field? I have seen some people do it with something resembling this: return true ? ... false
EDIT:
Okay, this is my code atm, haven't checked it yet since I need to do some other things to get it all up, but I think there may be a better way to do this.
public boolean isBandSelected(String name) {
// TODO Auto-generated method stub
Cursor cursor = mDb.query("bands", new String[] { "selected" }, "name="
+ name, null, null, null, null);
int index = cursor.getColumnIndex("selected");
String selected = cursor.getString(index);
return selected == "1";
}
You can use regular expression to match rows whose name field being string. Many databases can support regular expression.
The ternary operator(? :) can be used to make return statement like this.
return value == 0 ? false : true
But it depends on what kind of data type you what to return. Code above returns boolean data type.
The last line of your code above will always return false. This is because the == operator compares the reference of the two objects. you can use:
return "1".equals(selected);
I created database table in my android app. I used this query:
CREATE TABLE foo (_id INTEGER PRIMARY KEY AUTOINCREMENT, mybool BOOLEAN)
Than I added row to the table, that the value of mybool will be true.
I ran the sqlite3 command to see the value in the table, and I saw:
_id | mybool
----------------------
1 | 1
That is corret, the true value became to 1.
The strange thing is in the reading. I read the table like that:
ContentValues values = new ContentValues();
Cursor cursor = db.rawQuery("SELECT * FROM foo", null);
DatabaseUtils.cursorRowToContentValues(cursor, values);
Then I get strange result:
values.getAsBoolean("mybool"); // return false - WRONG
values.getAsInteger("mybool"); // return 1 = true - CORRECT
I use the code like that to get boolean value:
values.getAsInteger("mybool") != 0;
But it's strange.
Why I get always false in the getAsBoolean function? Is there any bug in the ContentValues class? Anyone else having this problem?
DatabaseUtils.cursorRowToContentValues() stores everything as strings (except blobs). ContentValues.getAsBoolean() will attempt to convert the string to a boolean (using Boolean.valueOf()), but that only works if the string is equal to "true", not "1".
This looks like an Android bug to me.
You've skipped some code here.
What's your proof that values.getAsBoolean("mybool") returns false? You have to return a Boolean. How are you checking it?
ContentValues.getAs returns a value if the key can be found, or null if it can't or if the value can't be converted. Be sure that you're doing a full test.
getAsBoolean does not return a boolean but a Boolean wrapper object, which can be either null, Boolean.FALSE, or Boolean.TRUE.
If you can ensure that there aren't NULLs, use values.getAsBoolean("mybool").booleanValue() to get the actual value.
I don't know if it's the best solution for this problem, but this code below works for me:
Integer result = contentValues.getAsInteger(attributeName);
if(result == null || result == 0) {
parameter = false;
} else {
parameter = true;
}
Get boolean result like below:
boolean result = values.getAsInteger("mybool") == 1;
I try to get an Item out of my SQL db in android, everything goes well, the only thing I am struggling with is to get the INTEGER value is there is nothing filled in in the DB (null?)
So I first initialize it, then get the Integer value out of the DB and then assign it to an instance of my class. I was once told that if it will get nothing out of the DB it will keep the initialized value, but this might be wrong? I use now:
int score = 100;
score = c.getInt(11);
q.setScore(score);
I was once told that if it will get nothing out of the DB it will keep the initialized value
That is true for Embedded SQL. You seem to be using a resultset object, so it is not true.
Resultset objects typically return 0 if you try to get a numeric null value from a column.
Use c.wasNull() to check if the value you just read was null and not 0.
EDIT (added the code from Jack's comment):
int score;
if (c.isNull(11)) {
score = 100;
} else {
score = c.getInt(11);
}
q.setScore(score);
http://developer.android.com/reference/android/database/Cursor.html#getInt(int)
*public abstract int getInt (int columnIndex) Since: API Level 1 Returns the value of the requested column as an int. The result and
whether this method throws an exception when the column value is null,
the column type is not an integral type, or the integer value is
outside the range [Integer.MIN_VALUE, Integer.MAX_VALUE] is
implementation-defined. Parameters columnIndex the zero-based index of
the target column. Returns the value of that column as an int.*
Can an Android Cursor return a boolean value? I've looked at the docs and there was no info on it?
If not - then is there an alternative way to get a boolean value from a SQLite table?
The android implementation of SQLite3 doesn't properly support boolean values. You will need to use integers set to 0 or 1 and write some code to convert that to a boolean e.g.
int x = cursor.getInt(...);
return x == 1;
Use enum type with values 'Y' and 'N' to represent the boolean value
Another way is just to pass as String rather than boolean and then parse it back to boolean:
int index = cursor.getColumnIndex(<key>);
String str = cursor.getString(index);
boolean bool = Boolean.parseBoolean(str);