SQLlite in android SUM select not working properly - android

I wanna get the sum of KEY_REC_VAL from table MMDatabaseHelper.TABLE_RECORD. My code is resulting in fatal error and I have no idea how to solve it. Any ideas? Thank you.
public Integer getIncomesSum()
{
String col = MMDatabaseHelper.TABLE_RECORD+"."+MMDatabaseHelper.KEY_REC_VAL;
String whereClause = " WHERE " +TABLE_RECORD+"."+KEY_REC_VAL+" >"+" 0";
String query = "SELECT sum ("+col+
") FROM "+TABLE_RECORD+
whereClause;
Log.i("SQL",query);
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = null;
try {
cursor = db.rawQuery(query,null);
} catch (SQLiteException e) {
} finally {
} return cursor.getInt(0);
Here is the error:
ERROR: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1

before return statement add this line cursor=cursor.moveToFirst();

Related

Error in accessing data from cursor in SQLite

I am working on a SQLite program and getting an error saying
2019-07-14 21:07:37.465 13538-13538/? E/CursorWindow: Failed to read row 0, column -1 from a CursorWindow which has 1 rows, 2 columns.
2019-07-14 21:07:37.466 13538-13538/? D/AndroidRuntime: Shutting down VM
2019-07-14 21:07:37.467 13538-13538/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.xyz.sqlitelist, PID: 13538
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.xyz.sqlitelist/com.example.xyz.sqlitelist.MainActivity}: java.lang.IllegalStateException:
Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
.
.
Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
W/ActivityManager: Force finishing activity com.example.xyz.sqlitelist/.MainActivity
String databaseToString(){
StringBuilder dbString= new StringBuilder();
SQLiteDatabase db = getWritableDatabase();
String query=" SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
Cursor c=db.rawQuery(query,null);
c.moveToFirst();
while (!c.isAfterLast()){
if(c.getString(c.getColumnIndex("productname")) != null) {
c.moveToNext();
dbString.append(c.getString(c.getColumnIndex("productname")));
dbString.append("\n");
}
c.close();
db.close();
return dbString.toString();
}
Your column's name is "_productname" and not "productname" and this problem can be solved by not hardcoding this name since you have it in the variable COLUMN_PRODUCTNAME.
Also your code will miss rows because you use incorrectly moveToFirst(), moveToNext() and isAfterLast() when you only need moveToNext():
String databaseToString() {
StringBuilder dbString = new StringBuilder();
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
Cursor c = db.rawQuery(query, null);
int index = c.getColumnIndex(COLUMN_PRODUCTNAME);
while (c.moveToNext()) {
dbString.append(c.getString(index)).append("\n");
}
c.close();
db.close();
return dbString.toString();
}
Also that WHERE 1 in the sql statement is not needed unless you want to change it later to something meaningful.
you can change your code
String sql = " SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
Cursor c = getWritableDatabase().rawQuery(sql, null);
while (c.moveToNext()) {
if(c.getString(c.getColumnIndex("productname")) != null)
{
dbString.append(c.getString(c.getColumnIndex("productname")));
dbString.append("\n");
}
}
c.close();
db.close();
return dbString.toString();

android SQLite database java.lang.IllegalStateException?

Hi i am using SQlite database for my app.
and i want to retrieve max value of increment primary key i.e ROWID.
but when i write query for this i got this exception
10-21 11:02:50.062: D/IllegalStateException(2575): java.lang.IllegalStateException: get field slot from row 0 col -1 failed
my method for retrieving max value is
public String getMaxID(){
SQLiteDatabase db = this.getReadableDatabase();
String productName = SingleTonClass.getInstance().dummy_productname;
String QUERY = "SELECT max("+ROW_ID+") as ID FROM "+TABLE_NAME
+" where "+PRODUCT_NAME+ " = " + "'" +productName+ "'";
Log.d("Query for Get previous cost", ""+QUERY);
Cursor maxID = db.rawQuery(QUERY, null);
String max = null;
int temp = 1;
try{
while(maxID.moveToNext()){
max = maxID.getString(maxID.getColumnIndex(ROW_ID));
Log.d("MaxID", ""+max);
maxID.close();
}
// }
// return max;
}catch(IllegalStateException e){
Log.d("IllegalStateException", ""+e);
}finally{
// maxID.close();
/ db.close();
}
return max;
}
Please help me out.
Thanks.
Problem is here
max = maxID.getString(maxID.getColumnIndex(ROW_ID));
Change to this
max = maxID.getString(maxID.getColumnIndex("ID"));
You are trying to get this column:
max = maxID.getString(maxID.getColumnIndex(ROW_ID));
But in your query you are using an alias:
"max("+ROW_ID+") as ID"
Try doing the following:
max = maxID.getString(maxID.getColumnIndex("ID")));
Hope it helps

How to use th SUM function to return the values from sqlite DB in android?

In my application, store the amount details of company in my sq lite DB.For example om my first position of DB in name column-company 1,total column - 400,second position of DB in name column-company 2,total column - 800,third position of DB in name column-company 1,total column - 500.how Sum the company 1 details only to return the total amount.
My main coding is,
String str = db.company_amount("Company 1");
Log.v("Total", ""+str);
My DB coding is,
String company_amount(String name){
SQLiteDatabase db = this.getReadableDatabase();
String s = "";
Cursor cursor = db.rawQuery("SELECT SUM(KEY_AMOUNT) FROM TABLE_BILL_DETAILS WHERE = ?", new String[] {String.valueOf(name)});
if (cursor != null) {
if (cursor.moveToNext()) {
s = cursor.getString(1);
return cursor.getString(1);
}
cursor.close();
}
return s;
}
It shows some error,I don't know how to return the values.Can any one know please help me to solve this problem.
My Logcat Error
04-25 14:54:06.701: E/AndroidRuntime(2776): FATAL EXCEPTION: main
04-25 14:54:06.701: E/AndroidRuntime(2776): java.lang.RuntimeException: Unable to start activity
ComponentInfo{invoicebill.details/invoicebill.details.Total_company_details}: android.database.sqlite.SQLiteException: near "=": syntax error: , while compiling: SELECT SUM(KEY_AMOUNT) FROM TABLE_BILL_DETAILS WHERE = ?
SQLiteDatabase db = getReadableDatabase();
String sql = "SELECT SUM(KEY_AMOUNT) FROM TABLE_BILL_DETAILS WHERE name = ?";
long sum = android.database.DatabaseUtils.longForQuery(db, sql, new String[]{name});
WHERE = ?
This is incorrect SQL syntax. You forgot to specify which field you're comparing with the argument. I guess it's name or something similar, so correct syntax would be something like:
WHERE name = ?
you can use to get details using id like this.
public int getTotalOfAmount(int id) {
odb = dbh.getReadableDatabase();
Cursor c = odb.rawQuery("SELECT SUM(" + KEY_AMOUNT + ") FROM " + DATABASE_TABLE + " WHERE " + KEY_ID + " = " + id, null);
c.moveToFirst();
int i = c.getInt(0);
c.close();
return i;
}
.

SQLite select query with where cluase

I have the following function for SQLite select statement
public Boolean itemFound(String cartId,Long ItemId){
SQLiteDatabase db = this.getReadableDatabase();
Log.d("search",cartId+"--"+ItemId);
try {
String where = COL_ITEM_CART_ID+"='"+cartId+"' and "+COL_ITEM_ID+" ="+ ItemId+"";
Log.d("where===============", where);
String columns[] = new String[] { COL_ITEM_ID,COL_ITEM_NAME, COL_ITEM_PRICE, COL_ITEM_ADDDATE,COL_ITEM_QUANTITY,COL_ITEM_CART_ID }; // > null means * (all)
Cursor c = db.query(TABLE_NAME,
columns ,
COL_ITEM_CART_ID+"='?' and "+ COL_ITEM_ID + "=?" ,
new String[]{cartId,String.valueOf(ItemId)},
null,
null,
COL_ITEM_ADDDATE+" desc");
int numRows = c.getCount();
c.close();
db.close();
if(numRows>0)
return true;
else
return false;
} catch (SQLException e) {
db.close();
return false;
}
}
where the parameters are :
Long type itemId= 9882889921
String type cartId = ca1745ef-24eb-4da8-a1ea-9650d78ba5c0
Despite there is recode with these data. the returned rows is 0 , why ?
You have wrapped a ? in single quotes, change this:
COL_ITEM_CART_ID+"='?' and "+ COL_ITEM_ID + "=?"
The line above is trying to literally match COL_ITEM_CART_ID to a question mark, change it like this:
COL_ITEM_CART_ID + "=? and "+ COL_ITEM_ID + "=?"
The query method will sanitize your data input for you, so when you wrap the ?s with apostrophes, the apostrophes become part of the input string itself. This is causing your query to return 0 rows.
To fix the problem, remove change all instances of '?' to ?.

java.lang.IllegalStateException: get field slot from row 0 col -1 failed

I have table in sqlite that contain only one record and I want to access that in cursor but facing problem I got this exception java.lang.IllegalStateException: get field slot from row 0 col -1 failed
My code is here :
c2=sql.dis();
c2.moveToFirst();
name = c2.getString(c2.getColumnIndex(DbManager.displayname));
ListName.setText("selected list"+name);
}
and this in BD class:
public Cursor dis() {
try
{
SQLiteDatabase db= this.getWritableDatabase();
String[] todo = new String[] {displayName };
Cursor cursor=db.query(displayname, todo, null, null, null,null, null);
return cursor;
}
catch(Exception ex)
{
str = ex.toString();
}
problem of above code is in this line
name = c2.getString(c2.getColumnIndex(DbManager.displayname)); displayname is table name not a column name.

Categories

Resources