Database retreival in android - 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'

Related

Cannot use Like statement in Android SQLite with argument and % character

Caused by: java.lang.IllegalArgumentException: Cannot bind argument at index 1 because the index is out of range. The statement
has 0 parameters.
Android doesn't recognise ? character in ?%
I try to achieve this:
String selectQuery = "SELECT * FROM config WHERE Directory Like '?%';";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, new String[] {parent});
I have searched for a solution but couldn't find anything, I think it's pretty particullary. I am trying to do it like this because I want to make the query work with Strings that contains character '.
Maybe someone who had the same problem can answer me how can I solve this.
Use || to concat parameter and wildcard:
SELECT * FROM config WHERE Directory Like ? || '%';
SELECT * FROM config WHERE Directory Like '?' || '%';
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, new String[] {parent});
using || solves this issue
you can put what condition you have into a String variable and then pass it to your query like this--> String Condition="'?";
SELECT * FROM config WHERE Directory Like '"+Condition+"'

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;
}

SQL query with WHERE and LIKE not working

Hi I am developing an android app.I have a DB table NUMBERRECEIVED with a field phnnofrmDb VARCHAR. I need to compare these db numbers with the phone numbers entered by the user in a textview.
This is what is the code I am trying
while (c.moveToNext())
{
//phone number entered in text view
**contactNumber**
db = openOrCreateDatabase("Test", 0, null);
Cursor cur = db.rawQuery("SELECT count(*) FROM NUMBERRECEIVED ", null);
if (cur.getCount() > 0)
{
Cursor cursor = db.rawQuery("SELECT phnnofrmDb FROM NUMBERRECEIVED WHERE phnnofrmDb Like '%contactNumber' ", null);
if (cursor != null && cursor.moveToFirst())
{
phnnofrmDb = cursor.getString(cursor.getColumnIndex("phnnofrmDb "));
if(phnnofrmDb.contains(r_address))
{
Log.e("same","true");
}
else if(!phnnofrmDb.contains(r_address))
{
Log.e("same","false");
}
}cursor.close();
} cur.close();
db.close();
}c.close();
But the Log says "true" always. I may be going wrong in the query. Please suggest how to resolve this and the user may enter numbers like +9195** or +44**** or just the number like 81****. How do I compare them excluding the + and country code(+91). Please Suggest.
Thanks!
PhoneNumberUtils provides various methods to compare and format phone numbers.
In your case you can use toCallerIDMinMatch and getStrippedReversed functions.
You can look more into the documentation here.
Use libphonenumber library.
Google's common Java, C++ and Javascript library for parsing,
formatting, storing and validating international phone numbers.
https://code.google.com/p/libphonenumber/
Replace your query with:
Cursor cursor = db.rawQuery("SELECT phnnofrmDb FROM NUMBERRECEIVED WHERE phnnofrmDb Like '%'||?", new String[]{contactNumber});
NEVER hardcode user provided strings in your SQL statement.
You need a closing quotation mark at the end of the like expression:
"SELECT numberp FROM NUMBERRECEIVED WHERE phnnofrmDb Like '%contactNumber' "
Hope this helps :)
I think you missed singlecot( ' ) in the query
Like '%contactNumber
replace with
Like '%contactNumber'

Fetching last row from sqlite database

I am trying to fetch the last row from my SQLite database. Until now i have tried max,sql_sequence but nothing seems to work. I have to fetch the row values and assign it to a class variable.
Any help is appreciated as I am new to SQLite and Android.
Thanks..
If you have already got the cursor, then this is how you may get the last record from cursor:
cursor.moveToPosition(cursor.getCount() - 1);
then use cursor to read values
or
do it like this
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToLast();
or
SELECT * FROM TABLE WHERE ID = (SELECT MAX(ID) FROM TABLE);
This should do what you want:
SELECT *
FROM food_table
ORDER BY _id DESC
LIMIT 1
Try This It May Help You It Gives Last Record Of Your Table
Cursor mCursor = db.rawQuery("Select * from TableName", null);
mCursor.moveToLast();
Now Get The Data From The Cursor
There is usually a table called sqlite_sequence which stores the highest primary key of all the tables in the SQLite db. So use the following
String selectQuery = "SELECT * FROM sqlite_sequence WHERE name = table_name";
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToLast();
You can use modified query to in last row....but you have to sort in a order using any column like in my case I have a serial_no column in my Employee table so my query is
SELECT * FROM Employee ORDER BY serial_no DESC LIMIT 1
limit 1 is in your case because you want only last record only

Databasequery for retrieval

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\""

Categories

Resources