I'm trying to get sum of column in SQLite database - java

i want to get sum of column price but it show -2 in total price
//Dbhandler
public Cursor gettotalp()
{
SQLiteDatabase database = this.getReadableDatabase();
Cursor cursor =database.rawQuery("select sum(totalprice) as total from " + TABLE_Users + ";", null);
Log.d(TAG, "gettotalp: "+cursor.getCount());
return cursor;
}
//showallsaleitemActivity
Cursor cursor = db.gettotalp();
int m=0;
/* while (cursor.moveToNext()) {
m += cursor.getInt(cursor.getColumnIndex("totalprice"));
}*/
for(int k = 0; k<=cursor.getCount();k++) {
m += (int) Integer.parseInt(String.valueOf(cursor.getColumnIndex("totalprice")));
}
int i=m;
tp.setText("" + m);
database table image

Your primary issue is that the column name in the cursor does not match the column name passed to the getColumnIndex method.
Secondly the value you want is stored in the column of the Cursor, it is not the value of the index of the column in the Cursor. As it is the first and only column the index will be 0 and not the sum of the totalprice column. Instead you need to get the value stored in the column based upon the index of the column using one of the Cursor get???? methods in this case you want to use either getInt or getString (if you want to use the value for calculations then getInt means that you don't have to do the parseInt from a String, if you only want to display the value then getString could be used).
I personally prefer to get the value using the get method more appropriate to the type of value being retrieved. Hence as it's an integer value then I have used getInt even though it's being used as a string.
I would suggest the following 2 snippets of code be used :-
// DBHanlder
public int gettotalp() {
int rv = 0;
String total_column = "total_price";
SQLiteDatabase database = this.getReadableDatabase();
Cursor cursor =database.rawQuery("select sum(totalprice) as " + total_column + " from " + TABLE_Users + ";", null);
Log.d(TAG, "gettotalp: "+cursor.getCount());
if (cursor.moveToFirst()) {
rv = cursor.getInt(cursor.getColumnIndex(total_column));
}
cursor.close();
return rv;
}
chances of mistakes reduced by using a variable for the column name alias.
The Cursor moveToFirst method will move to the first row in the Cursor.
When a Cursor is returned from the SQLiteDatabase methods that create a Cursor the Cursor is at a position that is BEFORE the first row, so a move is required.
All the Cursor move???? methods return false if the move cannot be made.
A Cursor should always be closed when it is done with. Not doing so can lead to errors who's underlying cause (such as file handles exhausted) is difficult to determine.
2nd Snippet :-
//showallsaleitemActivity
tp.setText(Integer.toString(gettotalp()));
Note
Instead of using
cursor.getInt(cursor.getColumnIndex(total_column))
As you are only returning a single value you could use
cursor.getInt(0)
then the column name is then irrelevant (if valid for the SQL). Personally I prefer to not use hard coded index unless necessary or overly complex to not use them.

The column that returns the sum in your query is not totalprice.
You aliased it as total.
To get it, use this:
Cursor cursor = db.gettotalp();
cursor.moveToFirst()
int m = cursor.getInt(cursor.getColumnIndex("total"));
or, since the query returns only 1 column:
int m = cursor.getInt(0);
You don't need the for loop, which in your code adds twice -1 and returns -2 because cursor.getColumnIndex("totalprice") returns -1 (since the column does not exist).

Related

Issue with SQLiteDatabase.query() when SQLiteDatabase.rawQuery() works fine

I am having issue querying my SQLITE database in Android. I have a table called "resets" with some values in them. Currently I only have one entry.
reset_timestamp | interval
1479442048 | 5
This is the query I was trying to execute. However, it returns zero results when I call cursor.getCount(). The query I want to execute is:
SELECT reset_timestamp FROM resets WHERE (reset_timestamp=1479442048);
I don't really want to use rawQuery(). I want to use query(). Here is my query statement.
SQLiteDatabase db = new PowerDbHelper(this).getWritableDatabase();
String[] resetsQueryColumns = {"reset_timestamp"};
String[] resetsQuerySelectArgs = {"1479442048"};
Cursor cursor = db.query("resets", resetsQueryColumns, "reset_timestamp=?",
resetsQuerySelectArgs, null, null, null);
However, getCount() returns 0 with this. On the other hand, this works fine and returns my result
cursor = db.rawQuery("select reset_timestamp from resets where (reset_timestamp=1479442048)", null);
and getCount() returns 1, what I want. Putting quotes around '?' gives me
java.lang.IllegalArgumentException: Cannot bind argument at index 1 because the index is out of range
What am I doing wrong with query()?
"1479442048" is a string (you even wrote String in front of it). A string and a number are not equal.
The query function supports only string parameters, so you have to convert the string back into a number:
query(..., "reset_timestamp=CAST(? AS INT)", ...);
Alternatively, insert the number directly into the query:
query(..., "reset_timestamp=1479442048", null, ...);

Set java variable depending on sql return value

I have the following problem:
I need to set a boolean true is an entry in a database exists.
ResultSet rc1 = null;
int Counterval;
String url = "jdbc:db2://localhost:50000/dbname";
Connection conn = DriverManager.getConnection(url,"","");
Statement st = conn.createStatement();
String sqlmd="select count(*) as Counter from tablename where mdsum = '"+mdSum+"' and filename = '"+Filename+"'";
rc1=st.executeQuery(sqlmd);
Counterval=rc1.getInt("Counter");
System.out.println("VAL: "+Counterval);
conn.close();
I get the following error message:
[jcc][t4][1090][10899][4.19.26] Illigal operation to read at the current cursor position. ERRORCODE=-4476, SQLSTATE=02501
How can I do this?
I use DB2 if that is of importance
Thanks for your help in advance.
TheVagabond
I don't know if you've tried the code, but if you did, what kind of exception are you getting?
You should try st.executeQuery instead of st.executeUpdate and then just compare if the returning number of count() function is bigger than 0
EDIT:
Seeing now your exception in your edited question:
A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.
if (rc1.next()){
booleanVariable = true;
}
This will set the boolean variable in true if the variable resultSet (rc1) is returning something, it means that in the database there is data according to the query you made. If it returns false then it is empty.
I hope it can help you. Greets.
You should callResultSet.next() method first to move the cursor to the first row.
boolean check;
String sqlmd="select count(*) as Counter from tablename where mdsum = '"+mdSum+"' and filename = '"+Filename+"'";
rc1=st.executeQuery(sqlmd);
rc1.next();
Counterval=rc1.getInt("Counter");
if(Counterval > 0){
// do something
}else{
// do something
}
System.out.println("VAL: "+Counterval);
According to docs of next method -
Moves the cursor forward one row from its current position. A
ResultSet cursor is initially positioned before the first row; the
first call to the method next makes the first row the current row; the
second call makes the second row the current row, and so on.
For better understanding read this answer.

Android Cursor - Two floats not adding if they are equal?

This is a strange problem, and I hope it has a simple solution. I have a database with encrypted values. I have created a cursor that will go through each of the entries in a table, decrypt the value from the column I need, and add the value to a variable, "total". I want the sum of all of the values in the column. Here is the code:
while (c.moveToNext())
{
strTotal = c.getString(c.getColumnIndexOrThrow(KEY_TOTAL));
strTotal = sc.decrypt(strTotal);
total = Float.valueOf(strTotal) + total;
}
Now, here's the strange part. Let's suppose I have two values in the database: 2 + 4. After each is decrypted, it will correctly add them: 6. Now, if the values are equal: 2 + 2, for instance, the method returns "2" instead of "4". This happens even if it is off by a decimal (2 + 2.01 = 4.01, but 2 + 2 still outputs 2 for example).
Is there something I am missing here? Thanks!
EDIT:
I've changed the code around just to see if the decryption was the problem and it is still giving me the same result:
float total = 0;
String strTotal = "10";
while (c.moveToNext())
{
try {
//strTotal = sc.decrypt(c.getString(c.getColumnIndex(KEY_TOTAL)));
total = Float.valueOf(strTotal) + total;
} catch (Exception e) {
Log.e(TAG, "exception", e);
}
}
This code is returning "10", even though there are 3 entries in the database! It looks like if two rows in the database have the same value in the KEY_TOTAL field, it is returning less results. Here is the query:
Cursor c = mDb.query(true, DATABASE_TABLE, new String[] {KEY_TOTAL}, KEY_TYPE + "=" + t, null, null, null, null, null);
If I pull the db and open it with a sqlite browser, and SELECT all of the rows, I am getting 3 still, however.
I just checked the SQLite documentation for Android (I'm not an Android developer) and I think I found your problem. The first argument to the query method is whether to select distinct rows. Since you're passing TRUE and you're only selecting one column, duplicates will be removed from the result, which is not what you want.
Changing your call to query to the following should fix your issue.
Cursor c = mDb.query(false, DATABASE_TABLE, new String[] {KEY_TOTAL},
KEY_TYPE + "=" + t, null, null, null, null, null);
Have you checked for thrown exceptions? Especially NumberFormatException? I'm guessing there is some other logic problem that is causing the loop to exit prematurely.

Complex WHERE condition in Android cursor query

I want to query the Contacts data and retrieve a contact name and a phone number with the following condition: if a contact has a mobile number then pick that number, else pick any number/first number the contact has. Is it possible to formulate this condition in a cursor query or would I have to do it within a custom cursor adapter?
This is the code I have at the moment. It works fine but it retrieves all numbers for all contacts, therefore I get duplicate names if a person has more than one contact.
private String WHERE_CONDITION = ContactsContract.Data.MIMETYPE + " = '" +
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "'";
private String[] PROJECTION = {ContactsContract.Data.DISPLAY_NAME,
ContactsContract.Data.DATA1, ContactsContract.Data._ID };
private String SORT_ORDER = ContactsContract.Data.DISPLAY_NAME;
cursor = this.getContentResolver().query(
ContactsContract.Data.CONTENT_URI, PROJECTION, WHERE_CONDITION, null, SORT_ORDER);
Any help is much appreciated!
It would be much easier and simpler to put this logic in Java. Just retrieve all numbers and select the one you need. Typically you will have at most 3 numbers, may be 5. In any case overhead will be very low.

Fetching a SQLite SUM in Java on Android

I'm new to SQLite and Java, and I'm trying to learn things on the fly. I have a column that has some numeric values in it, and I would like to get the sum of it and display it in a textview.
My current code is this:
public Cursor getTotal() {
return sqliteDatabase2.rawQuery(
"SELECT SUM(COL_VALUES) as sum FROM myTable", null);
}
I'm not sure if that code is correct, though.
I know that I'm supposed to fetch the results of that code, but I'm unsure how to do it. How can I get the results of this query into my Java code?
The sum will be returned as a result with one row and one column so you can use the cursor to fetch that value:
Cursor cursor = sqliteDatabase2.rawQuery(
"SELECT SUM(COL_VALUES) FROM myTable", null);
if(cursor.moveToFirst()) {
return cursor.getInt(0);
}

Categories

Resources