Reading a value from a database - android

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);

Related

moveToFirst does not work

I am using moveToFirst and it works very well. But this sql query doesnt work. I don't know why. I didn't receive any error.
My query
String sqlKomut = "SELECT SHareket.*,CHareket.[Meblag],Cari.AnlikBakiye FROM CHareket , SHareket,Cari WHERE CHareket.[CariID]=SHareket.[CariID]=Cari.[CariID]= '"+cari.getCariID()+"' AND SHareket.[Seri]='"+hareket.getSeri()+"' AND SHareket.[Sira]='"+hareket.getSira()+"'AND SHareket.[Tip]='"+hareket.getTip()+"' AND SHareket.[Cins]='"+hareket.getCins()+"' ORDER BY SHareket.[Satir]";
and I get my cursor getValue here:
Cursor cursor = db.rawQuery(sqlKomut, null);
if(cursor !=null){
if(cursor.moveToFirst()){
do {
eleman.setStrEleman(cursor.getString(cursor.getColumnIndex("Seri")));
eleman.setIntEleman1(cursor.getInt(cursor.getColumnIndex("Sira")));
eleman.setIntEleman2(cursor.getInt(cursor.getColumnIndex("CariID")));
eleman.setIntEleman10(cursor.getInt(cursor.getColumnIndex("Cins")));
eleman.setIntEleman11(cursor.getInt(cursor.getColumnIndex("Tip")));
eleman.setIntEleman11(cursor.getInt(cursor.getColumnIndex("Satir")));
eklenenfaturalar.add(eleman);
} while (cursor.moveToNext());
}
}
WHERE CHareket.[CariID]=SHareket.[CariID]=Cari.[CariID]= '...'
You cannot do multiple comparisons in a single expression like that.
(The comparison returns a boolean value, 0 or 1; any more comparisons will then use this boolean instead of an ID value, e.g., you end up with something like 1=Cari.CariID.)
To use multiple comparisons, connect them with AND (as you already did with the other ones):
WHERE CHareket.[CariID]=SHareket.[CariID]
AND SHareket.[CariID]=Cari.[CariID]
AND Cari.[CariID]='...'
...

How to determine if a column is boolean from cursor object?

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

How to get specific rows from ContentProvider?

I am a little new to using content providers. I was wondering how I would get specific rows from a content provider?
For example how would I get the first row of my provider?
This is what I tried but It isnt working:
final Cursor cursorConversations = getActivity().getContentResolver()
.query(CONTENT_URI, null, null, null, null);
Toast.makeText(
getActivity(),
cursorConversations.getString(cursorConversations
.getColumnIndex(Columns.TITLE)),
Toast.LENGTH_LONG).show();
you simply use cursor move methods ex:
cursorConversations.moveToFirst();
cursorConversations.moveToPosition(0);
cursorConversations.moveToNext(); // <-- if at beginning position
just to make this answer a little more meaty, a popular technique used to loop through the rows of the cursor 1 by 1 from the beginning is:
while (cursorConversations.moveToNext()) {
// do something
}
Because the moveToNext() method (as well as other move methods) return a boolean, the loop will exit when the last row has been reached and can no longer moved to the next. effective and easy on the eyes too. One more tip: the cursor starts at the -1 index, before the first position of a zero-based query index results.
use something like this:---
if(cursorConversations.moveToFirst()){
int size=cursorConversations.getCount();
for(int i=0;i<size;i++){
cursorConversations.getString(cursorConversations
.getColumnIndex(Columns.TITLE));
cursorConversations.moveToNext();
}
}
cursorConversations.close();
Or
while(cursorConversations.moveTonext())
{
cursorConversations.getString(cursorConversations
.getColumnIndex(Columns.TITLE));
}

Android - Database with ContentValue with boolean bug?

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;

Android do while loop

Hi This my second question here.
I have the following table
|-----|-------|------|------|
|._id.|..INFO.|.DONE.|.LAST.|
|..1..|...A...|...N..|......|
|..2..|...B...|...Y..|..L...|<--- cursor.moveToPosition((int)_id-1);
|..3..|...C...|...Y..|......|
|..4..|...D...|...Y..|......|
|..5..|...E...|...N..|......|
|..6..|...F...|...N..|......|
|-----|-------|------|------|
I use the code:
cursor = db.query(TABLE_NAME, new String[]{INFO,DONE,LAST},null,null,null,null,null);
cursor.moveToPosition((int)_id-1);
String Yval = cursor.getString(cursor.getColumnIndex(DONE));
do
{
cursor.moveToNext();
Yval= cursor.getString(cursor.getColumnIndex(DONE));
}
while (Yval=="Y");
s = Yval;
I initially point the cursor to the LAST row I accessed, then I make a loop to go through the values in the DONE column, not stopping if there are Y's in the row of the column. When an N appears in the loop, the loop should stop.
But it doesn't work.
Yval never equals "Y". So the cursor does one 'moveToNext' and then exits the loop, because it doesn't read Yval as a "Y".
(I also changed everything to integers. 1 for N, and 0 for Y, but it still didn't work)
So what am I doing wrong here?
So you have to use equals() method if you want to compare Strings
while (Yval.equals("Y"));
You should know that:
== tests for reference equality.
equals tests for value equality.
So you want to test if Yval String has Y value so you have to use equals() method.
You approach doesn't work bacause:
String data = "lorem";
data == "lorem" ==> FALSE
data.equals("lorem") == TRUE
Also make sure that your Cursor has valid row so you need to add to condition also cursor.moveToNext() so
cursor.moveToNext() && (Yval.equals("Y")
also you need to treat cursor.moveToPosition((int)_id-1) so add it to condition.
I recommend changing a few things:
if(cursor.moveToPosition((int) _id - 1)) {
int doneIndex = cursor.getColumnIndex(DONE);
String Yval;
do {
Yval = cursor.getString(doneIndex);
} while(Yval.equals("Y") && cursor.moveToNext());
}
You should check if a row exists at position _id - 1 since the SQLite _id is a unique id, not the position of a row in a Cursor.
You only need to fetch the index of the DONE column once, simply store it in a local variable.
As deceiver mentioned, String are tested with equals() and similar methods.
You need consider what happens if all of the rows are "DONE", then you must stop trying to read the Cursor before an out of bounds exception is thrown.

Categories

Resources