No result on sqlite query - android

Hi all
I create a table like that
private static final String CREATE_TABLE_PRODUCT =
"create table prod (id integer primary key,titre text not null, desc text, is_free integer);";
i update it this way
SQLiteDatabase db = getConnection();
ContentValues updateEvent = new ContentValues();
updateEvent.put("is_free", 1);
int ok = db.update(prod, updateEvent, "id=?",
new String[] { Long.toString(evenement.getId()) });
db.close();
I do see the change in eclipse with DDMS questoid
but when i try to retrieve the value I get nothing ....
Cursor c = db.query(prod, new String[] { "id",
"titre", "desc", "is_free", },
"is_free=?", new String[] {"1"}, null, null,
null);
I've tried some variant like
String query = "SELECT * FROM "+EVENEMENT_TABLE+" WHERE is_free=1;";
Cursor c = sdb.rawQuery(query, null);
with no success
is this problem come from the type (integer) of my column ?
Any help

Do not use reserved keywords like desc in your queries. This probably causes query to fail.
In case you don't know update will not add values to the table. Use insert instead.

Related

Android SqlLite check if two values exist in 2 different columns

I am developing an application where the user inputs title and the date. I want to prevent the duplicated titles being inputted on the same day in to database. I am checking if the title exists on the selected date. However my query seems not to work and i don't know why, the application just crashes.Is this query correct? Can someone help?
public boolean checkExist(String title, String date) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery("SELECT * FROM "+TABLE_NAME+" WHERE "+TITLE+"=?" +"AND" + DATE+"=?", new String[] {title,date});
boolean exists = c.moveToFirst();
c.close();
return exists;
}
One issue that you have is that c.moveToFirst will always fail if a match does not exist as you are trying to move to a row in an empty cursor.
The resolution is to not use c.moveToFirst and instead get the count of the rows and then set the return value accordingly.
e.g.
public boolean checkExist(String title, String date) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery("SELECT * FROM "+TABLE_NAME+" WHERE "+TITLE+"=?" +"AND" + DATE+"=?", new String[] {title,date});
boolean exists = c.getCount() > 0;
c.close();
return exists;
}
The second issue is that the query itself is wrong as you do not have spaces either side of the AND keyword. That is instead of
Cursor c = db.rawQuery("SELECT * FROM "+TABLE_NAME+" WHERE "+TITLE+"=?" +"AND" + DATE+"=?", new String[] {title,date});
You should have
Cursor c = db.rawQuery("SELECT * FROM "+TABLE_NAME+" WHERE "+TITLE+"=?" +" AND " + DATE+"=?", new String[] {title,date});
Personally, I setup constants for SQL keywords that include the space and then use these. So I'd have something along the lines of +TITLE+"=?" + SQLAND + DATE+"=?". Where SQLAND would be defined along the lines of String SQLAND=" AND ";
PS look at Cricket_007's answer, the code is neater/better it's easier to read.
Your spacing is off. TITLE+"=?" +"AND" + DATE becomes TITLE=?ANDDATE=?
I would suggest this. See DatabaseUtils.queryNumEntries
public boolean checkExist(String title, String date) {
SQLiteDatabase db = getReadableDatabase();
String[] args = new String[] {title,date};
String filter = String.format("%s=? AND %s=?", TITLE, DATE);
return DatabaseUtils.queryNumEntries(db, TABLE_NAME, filter, args) > 0;
}
you should be using c.getCount() instead of c.moveToFirst()
if the value is greater than 0, then it exists

Getting an SQLite working within Android and accessing data

I am trying to get an SQLite database to work in Android and have a few questions!
I have put the following in the onCreate method of my database class, which extends SQLiteOpenHelper.
db.execSQL("CREATE TABLE IF NOT EXISTS `challenge` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `date` TEXT )");
I then have the following method.
public void addChallenge(){
SQLiteDatabase db = this.getWritableDatabase();
Date cDate = new Date();
String fDate = new SimpleDateFormat("yyyy-MM-dd").format(cDate);
ContentValues values = new ContentValues();
values.put("date", fDate);
db.insert("challenge", null, values);
}
And the following would grab the challenge added above back.
public int getChallengeId(){
SQLiteDatabase db = this.getWritableDatabase();
Date cDate = new Date();
String fDate = new SimpleDateFormat("yyyy-MM-dd").format(cDate);
String countQuery = "SELECT id FROM challenge WHERE date = " + fDate;
Cursor cursor = db.rawQuery(countQuery, null);
int challenge_id = 0;
if(cursor.moveToFirst()){
challenge_id = cursor.getInt(0);
}
return challenge_id;
}
My issue is that the challenge ID is returning as 0.
So I have a few questions.
Where is the database stored by default within Android?
Am I calling this correctly?
The code I use to access the above methods is as follows
Database db_add = new Database(context);
db_add.addChallenge();
db_add.close();
Database db_get = new Database(context);
challenge_id = db_get.getChallengeId();
db_get.close();
Any ideas?
Thanks.
The SQL query is not correct.
2015-02-23 tells the database that you want to subtract the numbers 2 and 23 from the number 2015.
Strings must be 'quoted'.
However, you should avoid such formatting problem by using parameters:
String countQuery = "SELECT id FROM challenge WHERE date = ?";
Cursor cursor = db.rawQuery(countQuery, new String[]{ fDate });

Complex queries with SQLite in Android

I have a table with 3 columns "ID", "NAME" & "STATUS". I would like to execute a query on my database where I can get only one entry of "ID" which is located at the top row. I have a working sql query,
"SELECT TOP 1 ID from SAMPLE_TABLE WHERE Status='PENDING' ORDER BY ID ASC;"
This is so far what I implemented in android,
// Getting pending items
public int pendingContact() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor mCount = db.query(
TABLE_CONTACTS ,
new String[] { "id" } ,
"status = ?" ,
new String[] { "PENDING" } ,
null ,
null ,
null
);
mCount.moveToFirst();
int count = mCount.getInt(0);
mCount.close();
return count;
}
Al through it gives the desired output but I would like to know if there is any other way of doing this more efficiently.
You can use Limit
public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
limit - Limits the number of rows returned by the query, formatted as LIMIT clause. Passing null denotes no LIMIT clause.
You can do this:
Cursor mCount = db.query(TABLE_CONTACTS, new String[] { "id" }, "status = ?", new String[] { "PENDING" }, null, null, "id ASC", "1");
This will keep you from acquiring more data than you need.
When you use ORDER BY, the database will read and sort all PENDING items before it can return the first one.
When using MIN, nothing but the smallest value must be stored temporarily:
SELECT MIN(id) FROM Contacts WHERE Status = 'PENDING'
In code:
Cursor mCount = db.rawQuery("SELECT MIN(id) FROM Contacts WHERE Status = ?",
new String[] { "PENDING" });

How to pass multiple values to query dynamically in android?

In my project I have to select multiple values and pass it to a query. i.e page1 contains checkboxes. I am storing the selected checkbox id's into an array.
I am shuffling that array and getting the values randomly. Now I need to pass these random values to a query. Using IN operator in database I can pass the values
statically but how can I pass the values dynamcially to the query.
For ex:(Passing values statically)
SELECT * FROM Persons WHERE person_id IN ('21','22')
In the above query the id's 21 and 22 are know previously and so we are passing statically but I want to send the values to query dynamically.
Page1:
public static ArrayList<String> chksublist = new ArrayList<String>();
Page2:
Collections.shuffle(chksublist );
SELECT * FROM Persons WHERE person_id IN ('21','22')
In the above line I want to send the random values which are in chksublist array.
String query = "SELECT * FROM Persons WHERE person_id IN (" + TextUtils.join(",", chksublist) + ")";
But shuffling the chksublist before sending it to your SQL query has no impact on the result set you get from SQL. It will not randomly permute your results. Remove Collections.shuffle(chksublist); and use
String query = "SELECT * FROM Persons WHERE person_id IN (" + TextUtils.join(",", chksublist) + ") ORDER BY RANDOM()";
see how values are dynamicaly passed
// Getting single contact
public Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
// here new String[] { String.valueOf(id) } value is added dynamicaly which is passed to the function
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
You can generate your query like this
int values[]; //it contains your generated values like 21,22....
String query="SELECT * FROM Persons WHERE person_id IN (";
for(int i=0;i<values.length;i++){
query=query+"'"+values[i]+"'";
if(i<values.length-1){
query=query+","; //No , after last values
}
}
query+=")";
finally pass this query.
Try it
cursor = database.query(tablename,
new String[] {"TopName"}, "id IN(?,?)", new String[]{"2","3"}, null, null, null);
using raw query
String query = "SELECT * FROM Persons WHERE person_id IN ("+parameter1+","+parameter2+")";
db.rawQuery(query);

Edit SQLite database record

How can I edit a particular record in a SQLite table given, Database Name, Table Name, int _id ,Column Name and Desired value of record?
EDIT:
My solution was database.update(DataBaseHelper.VFS_DATABASE_TABLE, values, "_id=?", new String[] {id+""});
public int deleteCpShadowEntryById (int id) {
int delRows = mDb.delete(<your_table_name>, "_id" + "=?", new String[] {String.valueOf(id)});
return delRows;
}
But I guess you do not want to delete. You want to update your value. So in this case you should at first select your row, fill the values of this row into a new ContentValues, replace you old value with new and update the row.
Edit: Maybe try this:
ContentValues args = new ContentValues();
args.put(<your_columnName>, newValue);
db.update(<your_table_name>, args, "_id" + "=?", new String[] {String.valueOf(id)});
Should be a simple bit of SQL:
DELETE FROM <table name> WHERE <column name> = <desired value>
SQLiteDatabase has a delete method :
public int delete (String table, String whereClause, String[] whereArgs)
If you have id of the particular record the code would be something like :
String whereArgs[] = new String { id };
db.delete(TABLE_NAME, "_id = ?", whereArgs);

Categories

Resources