Search code examples
androidmysqlsqlitesimplecursoradapterandroid-cursor

Can any one help me with these Database query


I wanted to get the result of this Cursor Database query in String or int values but couldn't. I know about coursor.getstring or getint but i am having probelm applying in the below case and query function. Below is the function with query.. I made my database java activity and this method was in it...

public Cursor getUpdatedAmount(){
String amountQuery="select sum(amount) from travelling_exp where call_id=1;";
Cursor cursor = myDatabase.rawquery(amountQuery,null);
return cursor;
}

The Query is Working fine without any error. Basically i wanted the sum of amount column after deletion or changes to my database, save and show the sum value in a edittext. But the problem is i cannot convert cursor value to a value string or int.

this is how i implemented the above DB Query function in my other java file until now :

Cursor cursor = myDB.getUpdatedAmount();

The fucntion returns the sum amount for ex if values in amount column is 1000,2000,3000 then the above query will return the sum = 6000. so i want to save and show that 6000 in an ediitext. I tried using .toString and finding other methods to work but no luck. Can anybody help me with this one. Its quite important for me and my project.

Thanks in advance


Solution

  • It's really not that difficult, if you would test out getInt(0) you'd see that you've got your answer, but here it is

    Since you're selecting only the SUM then only 1 column and 1 row will be returned, that's why getInt(0) works.

    public String getUpdatedAmount(){
        String amountQuery="select sum(amount) from travelling_exp where call_id=1;";
        Cursor cursor = myDatabase.rawquery(amountQuery,null);
        if(cursor.moveToFirst()){
            return "" + cursor.getInt(0);
        }
    }
    

    Notice: I've changed your function to return a String and not a Cursor

    So you can use it like this:

    txtTotal.setText(getUpdatedAmount());