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);
}
Related
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).
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, ...);
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.
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.
I'm trying to get the new rating from an UPDATE statement in java
int userID = 99;
String sql = "UPDATE table SET rating=rating+1 WHERE user_REF="+userID;
statement.executeUpdate(sql);
I can just do another SELECT statement, but isn't there a better way to retrieve the value or row while updating?
In short, No, there is no way to do this with ANSI standard SQL.
You have three options:
1) Do it in two queries - the update, then the select
2) Create a stored procedure that will execute the update and then return the select
3) Use a DB-specific extension, such as the PostgreSQL RETURNING clause
Note that options 2) and 3) are database-specific.
In MySQL:
$query1 = 'UPDATE `table` SET rating = (#rating:= rating) + 1 WHERE id = 1';
$query2 = 'select #rating';
thanks for the replies everybody, i ended up doing it like this:
int userID = 99;
String sql = "SELECT id, rating FROM table WHERE user_REF="+userID;
ResultSet rs = statement.executeQuery(sql);
rs.first();
float oldRating = rs.getFloat("rating");
float newRating = oldRating +1;
rs.updateFloat("rating", newRating);
rs.updateRow();
return newRating;
that way it (or at least seems so) does only one query to find the correct row, or am i wrong?
In PostgreSQL there is RETURNING clause
See: http://www.postgresql.org/docs/8.3/interactive/sql-update.html
Be cautious that most solutions are database dependent (Whether or not you want database independence in your application ofcourse matters).
Also one other solution you could try is to write a procedure and execute it as follows
my_package.updateAndReturnRating(refId, cursor record).
Of course this may/may not make the solution itself complicated but worth an "evaluation" atleast.