Databasequery for retrieval - android

I have the following query to retrieve data from a database.
But it is always returning as 0.
Please help me.
My query:
System.out.println("passed="+grp);
long sum=0;
Cursor cursor1 = db.rawQuery(
"SELECT SUM("+(KEY_TOTAL)+") FROM incomexpense WHERE category='Income' AND groups='grp'",null);
if(cursor1.moveToFirst())
{
sum = cursor1.getLong(0);
}
cursor1.close();
String housetotal=String.valueOf((long)sum);
System.out.println("house="+housetotal);
return housetotal;
I checked the database there are 2 entries that are satisfying the above condition.
However, it is always returning as 0.

For String, USE LIKE, NOT = and, in SQLITE, use " not ' :
"SELECT SUM("+(KEY_TOTAL)+") FROM incomexpense WHERE category LIKE \"Income\" AND groups LIKE \"grp\""

Related

Trying to get raw id from an SQLite table where column name is given

I am trying to get this id from a table that has a column called "name". I tried various codes I found but I keep getting an empty cursor, which results in the exception:
CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0.
The last code I tried is
Cursor cursor = db.rawQuery( "select * from " + TABLE_NAME + " where name='"+name+"'", null );
cursor.moveToFirst();
int countryId = cursor.getInt(cursor.getColumnIndex("id"));
I'd love to get some guidance. If some information is missing I'll provide it.
Thanks!
First, use the recommended and safe way to supply the argument name, by using a ? placeholder:
Cursor cursor = db.rawQuery( "select * from " + TABLE_NAME + " where name=?", new String[] {name} );
Then use the result of the method moveToFirst() to check if the Cursor contains any row(s):
int countryId = -1;
if (cursor.moveToFirst()) {
countryId = cursor.getInt(cursor.getColumnIndex("id"));
}
Finally check the value of countryId.
A negative value means that the name was not found.
Of course this code will work if there are columns id and name in the table.

Why Sqlite return only last row not all rows data?

I don't know what's wrong with my code I follow the rule but I get wrong result. I want to search db and find all rows data but I only get last row from sqlite. my code to search database is bellow:
public ArrayList<ArrayList<ContractSaveDataFromDB>> ActiveContractData(String phone, String numberId)
{
ArrayList<ContractSaveDataFromDB> UserData = new ArrayList<ContractSaveDataFromDB>();
ArrayList<ArrayList<ContractSaveDataFromDB>> SendUserData =
new ArrayList<ArrayList<ContractSaveDataFromDB>>();
SQLiteDatabase db = this.getReadableDatabase();
String whereClause = "phone = ? AND numberId = ?";
String[] whereArgs = new String[]{
phone,
numberId
};
String orderBy = "activeContract";
Cursor res2=db.query("usersAccount",null,whereClause,whereArgs,null,null,orderBy);
res2.moveToFirst();
do{
UserData.clear();
int index;
ContractSaveDataFromDB contractSaveDataFromDB=new ContractSaveDataFromDB();
index = res2.getColumnIndex("buyAmount");
String buyAmount = res2.getString(index);
contractSaveDataFromDB.setBuyAmount(buyAmount);
UserData.add(contractSaveDataFromDB);
SendUserData.add(UserData);
} while(res2.moveToNext());
res2.close();
db.close();
return SendUserData;
I don't know what's wrong. I appreciate if you help me to solve my problem.
you already added where clause so maybe it is filtering your results try to remove it by change this
Cursor res2=db.query("usersAccount",null,whereClause,whereArgs,null,null,orderBy);
to this
Cursor res2=db.query("usersAccount",null,null,null,null,null,orderBy);
I believe that your issues is that you are trying to use an ArrayList of ArrayList of ContractSaveDataFromDB objects.
I believe that an ArrayList of ContractSaveDataFromDB objects would suffice.
It would also help you if you learnt to do a bit of basic debugging, as an issue could be that you are not extracting multiple rows.
The following is an alternative method that :-
uses the ArrayList of ContractSaveDataFromDB objects,
introduces some debugging by the way of writing some potentially useful information to the log
and is more sound, as it will not crash if no rows are extracted
i.e. if you use moveToFirst and don't check the result (false means the move could not be accomplished) then you would get an error because you are trying to read row -1 (before the first row) as no rows exists in the cursor.
:-
public ArrayList<ContractSaveDataFromDB> ActiveContractData(String phone, String numberId) {
ArrayList<ContractSaveDataFromDB> SendUserData = new ArrayList<ContractSaveDataFromDB>();
SQLiteDatabase db = this.getReadableDatabase();
String whereClause = "phone = ? AND numberId = ?";
String[] whereArgs = new String[]{
phone,
numberId
};
String orderBy = "activeContract";
Cursor res2 = db.query("usersAccount", null, whereClause, whereArgs, null, null, orderBy);
Log.d("RES2 COUNT", "Number of rows in Res2 Cursor is " + String.valueOf(res2.getCount()));
while (res2.moveToNext()) {
ContractSaveDataFromDB current_user_data = new ContractSaveDataFromDB();
current_user_data.setBuyAmount(res2.getString(res2.getColumnIndex("buyAmount")));
Log.d("NEWROW", "Adding data from row " + String.valueOf(res2.getPosition()));
SendUserData.add(current_user_data);
}
res2.close();
db.close();
Log.d("EXTRACTED", "The number of rows from which data was extracted was " + String.valueOf(SendUserData.size()));
return SendUserData;
}
If after running you check the log you should see :-
A line detailing how many rows were extracted from the table
A line for each row (if any were extracted) saying Adding data from row ? (where ? will be the row 0 being the first)
A line saying The number of rows from which data was extracted was ? (? will be the number of elements in the array to be returned)

SQLite query give different result from mysql

I have two table in my sqlite db here is the first table named supplier and here is the second table named product
what I want to do is I want to get the supplier_name in table product by selecting id_supplier in table_product. Here is my query SELECT table_supplier.id_supplier, table_supplier.supplier_name from table_invoice_in, table_supplier where table_invoice_in.id_product = '4' and table_supplier.id_supplier = table_invoice_in.id_supplier
and what I got from that query is I can get the id_supplier but supplier_name gives me 0 value, but when I try the query in mysql, I got the correct result. My question is :
Is this a limitation of sqlite or there are something wrong with my query?
Thank you in advance.
Try using a JOIN:
SELECT table_supplier.id_supplier, table_supplier.supplier_name FROM table_supplier JOIN table_invoice_in ON table_supplier.id_supplier = table_invoice_in.id_supplier WHERE table_invoice_in.id_product = '4'
The problem solved! When we try to query some column(s) from multiple table, make sure that we get the desired result by pointing directly to the column name. Here is my correct code
public Cursor SelectInvoiceInById(String id){
String query = "SELECT product_name from table_product, table_invoice_in where table_invoice_in.id_invoice_in = '"+ id + "' and table_product.id_product = table_invoice_in.id_product";
ReadDB();
cursor = database.rawQuery(query, null);
cursor.moveToFirst();
if(cursor.getCount() > 0){
while (!cursor.isAfterLast()){
Log.d("RESULT", String.valueOf(cursor.getString(cursor.getColumnIndex(SQLiteHelper.PRODUCT_NAME))));
cursor.moveToNext();
}
}
CloseDB();
return cursor;
}

Android: Getting row by id

I'm trying to get database row by it's ID, but somehow query doesn't return that row. The sql query SELECT * From Table1 Where _id = 100 works good, so I don't know what's the reason. Here is the code of the query:
String [] selectedArgs = new String [] {String.valueOf(selectedItemId)};
String selection = Tables.Table1.COLUMN_ID + "=?";
String [] columns = {Tables.Table1.COLUMN_ID, Tables.Table1.COLUMN_NAME};
Cursor c = foodDB.query(Tables.Food.TABLE_NAME, columns, selection, selectedArgs, null, null, null);
Does anybody have any suggestions?
The problem is that your ID field is a number, while the parameter is a string; the query function does not allow other parameter types for some strange reason.
Try using an expression like COLUMN_ID + " = CAST(? AS INTEGER)".
If your query had only one result column, you could use a separate SQLiteStatement object where you'd be able to use bindLong().
Just in case somebody need it, i have used rawQuery() method for such type of query to work, because query() doesn't work.

Database retreival in android

I am retrieving data from database using select query.My requirement is i have to sum the (total) column where group=household and category=Income.I have 1 entry in database which satisfy this condition.But it returns always 0.Please help me.
My query is:
long sum=0;
Cursor cursor1 = db.rawQuery(
"SELECT SUM("+(KEY_TOTAL)+") FROM incomexpense WHERE groups='Household' & category='Income'",null);
if(cursor1.moveToFirst())
{
sum = cursor1.getLong(0);
}
cursor1.close();
String housetotal=String.valueOf((long)sum);
System.out.println("house="+housetotal);
Try replacing the & with AND in the query.
I guess the query might not have worked because you have written '&' instead of 'and'

Categories

Resources