displaying integers in android using sqlite - android

I have a database that contains decimals. The column is set up as ".. decimal(5,2) not null. What I'm trying to do is to find the sum of the column and displaying it in a text field by using this code..
public int getTotal() {
Cursor cursor = sqliteDatabase2.rawQuery(
"SELECT SUM(thedata) FROM thetable", null);
if(cursor.moveToFirst()) {
return cursor.getInt(0);
}
return cursor.getInt(0);
}
However, when returned the value is a whole number. It should be something like 20.75 instead of just 20.
I'm not very familiar with SQLite, so please help.

On top of Xperimental's answer, you are calling getInt() on the Cursor, and you are returning and int from getTotal(). Here, int is shorthand for integer, what you refer to as a "whole number". If you want floating-point values, use getFloat() and return a float or Float.

SQLite doesn't know the datatype DECIMAL, so it could be possible, that it defaults back to the INTEGER datatype it knows. Try to use another datatype, which is recognized by SQLite. The datatypes SQLite knows can be found on the following page:
http://www.sqlite.org/datatype3.html

Related

how to settext of android textview to Integer

I used to set text of my text view the count of my database rows. but it gives me an error. what should i do?
In My Handler Method:
public Integer METHOD_NAME(){
Cursor c = database.rawQuery( "SELECT * FROM MY_TABLE", null);
Integer first=c.getCount();
return first;
}
In My Activity Code:
int COUNT=db.METHOD_NAME();
db.open();
MyTEXTVIEW.setText(COUNT);
db.close();/* what is my Codes problem?
How to make it without problem? */
While i set the text of text view to a String, it doesn't show me any errors.
Firstly you should call the db.open() befor making a query as pointed by user370305 Secondly your METHOD_NAME() returns an Integer where as your COUNT variable is an int .
So you can do
int COUNT=db.METHOD_NAME().intValue()
Or change the return type of METHOD_NAME() type entirely to int
Convert int into String,
MyTEXTVIEW.setText(String.valueOf(COUNT));
Actually setText() only accept int as resource when your string resource is declared in string.xml file.
Update: I also doubt your code, you have db.open() method call after db.METHOD_NAME();, so if db.open() is for opening database connection than you have to change the sequence of both statements.
Like,
db.open();
int COUNT=db.METHOD_NAME();
MyTEXTVIEW.setText(COUNT);
db.close();/* what is my Codes problem?

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]='...'
...

Assigning a value in SQLite cursor to a variable

Iam trying to find average of a column in my sqlite database.
Here is the code:
public void getAvgMileage(Prediction pd)
{
String [] columns = new String[]{KEY_ROW_ID, KEY_KM, KEY_FUEL_QTY, KEY_FUEL_PRICE, KEY_TOTAL_COST, KEY_MILEAGE, KEY_DATE,KEY_TANK_FULL};
predictionCursor = ourDatabase.rawQuery("SELECT AVG(_mileage) FROM fuel_table WHERE _mileage IS NOT NULL ORDER BY _id DESC LIMIT 5", null);
predictionCursor.moveToFirst();
if(predictionCursor!=null && predictionCursor.getCount()>0)
{
predictionCursor.moveToLast();
findAvgMileage = (Double.valueOf(predictionCursor.toString()));
pd.setpredictionMileage(findAvgMileage);
}
}
But Iam geting a NullPointerException.
Any help??
Thank you.
It doesn't look like you are getting the value out of the cursor for your SQL recordset
This line:
findAvgMileage = (Double.valueOf(predictionCursor.toString()));
looks like it's trying to take a double value of the tostring() of the actual cursor - which I don't think is going to usable or at least not parseable to Double. The return of Cursor.toString() may well be a null value.
replace the line with the following:
findAvgMileage = predictionCursor.getDouble(0);
This new line will fetch out the value in the first column of the current position of the curosr which in your SQL should be the average value you want.

Check if SQL integer field is empty

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

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