How to implement where clause on Android Query method? - android

I'm trying to query a word, for this I'm using the db.query method. But I want to use a WHERE clause. I've done like this on my code, but I guess there is something wrong there with my WHERE clause.
public String select(String wrd) {
String list = new String();
Cursor cursor = this.db.query(TABLE_NAME, new String[] {"word"},
"word like " + wrd + "", null, null, null, "id desc");
if (cursor.moveToNext()) {
do {
list = cursor.getString(0);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}
I'm calling this method in other class, parsing a String argument.
Cursor cursor = getContentResolver().query(CONTENT_URI, null, null, null, null);
String body;
if(cursor.moveToFirst()){
body = cursor.getString(cursor.getColumnIndexOrThrow("body")).toString();
if(body == ""){
Toast.makeText(getBaseContext(), "There is no words to save!", Toast.LENGTH_LONG).show();
}
else{
String words = this.dh.select("Testando");
StringTokenizer st = new StringTokenizer(body);
while(st.hasMoreTokens()){
if(words == st.nextToken())
Toast.makeText(getBaseContext(), "found! "+words+"", Toast.LENGTH_LONG).show();
this.dh.insert(st.nextToken());
Toast.makeText(getBaseContext(), "The set of words has been updated!", Toast.LENGTH_LONG).show();
}
StringBuilder sb = new StringBuilder();
sb.append("Set of words:\n\n");
sb.append(words + " ");
txtView.setText(sb.toString());
}
}

I believe the problem has to do with the double-quotes in the below code:
Cursor cursor = this.db.query(TABLE_NAME, new String[] {"word"},
"word like " + wrd + "", null, null, null, "id desc");
Try this
Cursor cursor = this.db.query(TABLE_NAME, new String[] {"word"},
"word like \"" + wrd + "\"", null, null, null, "id desc");
Or even better
Cursor cursor = this.db.query(TABLE_NAME, new String[] {"word"},
"word like ?",new String[] {wrd} , null, null, "id desc");
Edit:
Use single quote instead of double-quote in your WHERE clause. See here
Cursor cursor = this.db.query(TABLE_NAME, new String[] {"word"},
"word like \'" + wrd + "\'", null, null, null, "id desc");

Related

filter a listview populated from SQLite

i added a filter to my listview ( populated from sqlite ). i am using this method to fetch the records from sqlite
public Cursor fetchServicesByName(String inputText, String c) throws SQLException {
db = this.getReadableDatabase();
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = db.query(TABLE_SERVICE, new String[] {KEY_ID,KEY_NAME,
KEY_ADRESSE, KEY_EMAIL, KEY_NUMTEL, KEY_WEBSITE,KEY_IMAGE}, KEY_TYPE + "=?",
new String[] { c },null, null, null, null);
}
else {
mCursor = db.query(true, TABLE_SERVICE, new String[] {KEY_ID,KEY_NAME,
KEY_ADRESSE, KEY_EMAIL, KEY_NUMTEL, KEY_WEBSITE,KEY_IMAGE},
KEY_NAME + " like '%" + inputText + "%'" , null,
null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
this is working, but what i want to do is to filter by inputText and KEY_TYPE
i used this (instead of the last db.query ) but it didn't return anything
mCursor = db.query(TABLE_SERVICE, new String[] {KEY_ID,KEY_NAME,
KEY_ADRESSE, KEY_EMAIL, KEY_NUMTEL, KEY_WEBSITE,KEY_IMAGE},
KEY_NAME + " like ? and" + KEY_TYPE + " like ? " , new String[] { inputText, c},
null, null, null, null);
You need to check if your inputtext and keytype are null!
Aris your routine working when you fill out your inputtext and c vallue?

How to return multiple entries with same value from SQLite

This is what my database looks like, how would I return all of the rows that have the same string in the KEY_ALCOHOL column? After I get all of the rows, I need to randomly pick one and then display it.
I tried this:
DATABASE HELPER .JAVA
public Cursor getAlcohol(String alcohol) throws SQLException
{
Cursor mCursor =
myDataBase.query(true, DB_TABLE, new String[] {
KEY_ROWID,
KEY_ALCOHOL,
KEY_TYPE,
KEY_BRAND,
KEY_PRICE
},
KEY_ALCOHOL + "=" + alcohol,
null,
null,
null,
null,
null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
MAIN ACTIVITY .JAVA
myDbHelper.openDataBase();
Cursor c = myDbHelper.getAlcohol("Liquor");
if (c.moveToFirst())
{
do {
DisplayTitle(c);
} while (c.moveToNext());
}
myDbHelper.close();
}
public void DisplayTitle(Cursor c)
{
Toast.makeText(this,
"id: " + c.getString(0) + "\n" +
"ALCOHOL: " + c.getString(1) + "\n" +
"TYPE: " + c.getString(2) + "\n" +
"BRAND: " + c.getString(3) + "\n" +
"PRICE: " + c.getString(4),
Toast.LENGTH_LONG).show();
}
I was testing to see if this would simply return all of the rows with "Liquor" in the KEY_ALCOHOL column but instead it gave me a null pointer.
EDIT
Got it working!!
Here is what i came up with and it works!! Let me know if anything is wrong or you see a better way of doing it! Thanks everyone!
myDbHelper.openDataBase();
Cursor Test = myDbHelper.getAlcohol("Liquor");
int test7 = Test.getCount();
test9 = r.nextInt(test7);
Cursor c = myDbHelper.getTitle(test9);
if (c.moveToFirst())
DisplayTitle(c);
else
Toast.makeText(this, "No title found",
Toast.LENGTH_LONG).show();
myDbHelper.close();
I hope this works
public Cursor getAlcohol(String alcohol) throws SQLException
{
Cursor mCursor =
myDataBase.query(true, DB_TABLE, new String[] {
KEY_ROWID,
KEY_ALCOHOL,
KEY_TYPE,
KEY_BRAND,
KEY_PRICE
},
KEY_ALCOHOL + "=?",
new String[] { alcohol },
null,
null,
null,
null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
Look at structure
Cursor SQLiteDatabase.query(String table,
String[] columns,
String selection,
String[] selectionArgs,
String groupBy,
String having,
String orderBy,
String limit)
Your 'selection' was wrong. It resulted in WHERE KEY_ALCOHOL + "=" + alcohol = null since argument is separate.

Adding anything to Section String breaks the android SQLite DB query?

I'm new to Android and SQLite, too. I'm trying to write a method where the DB query gets a specific row from the DB. This version of the method works fine where Selection is set to null:
public String anotherTry(){
String[] columns = new String[]{ KEY_SDATE, KEY_SC, KEY_VE };
Cursor cursor = db.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
if (cursor != null){
cursor.moveToFirst();
result = result
+ cursor.getString(0) + "\n"
+ cursor.getString(1) + "\n"
+ cursor.getString(2) + "\n";
return result;
}
return null;
}
but if I put anything in the Selection argument, it crashes. For example:
public String anotherTry(){
String[] columns = new String[]{ KEY_SDATE, KEY_SC, KEY_VE };
Cursor cursor = db.query(DATABASE_TABLE, columns, KEY_ROWID + "=" + "8", null, null, null, null);
String result = "";
if (cursor != null){
cursor.moveToFirst();
result = result
+ cursor.getString(0) + "\n"
+ cursor.getString(1) + "\n"
+ cursor.getString(2) + "\n";
return result;
}
return null;
}
What's going wrong here? I'm trying to get the 8th row to be displayed. I've tried all the formatting combos that I can think of: KEY_ROWID + "=" + "8", KEY_ROWID = "8", and so on, but no luck. Thanks for any help!
try followin code, i think it wil work for u
Cursor cursor = db.query(DATABASE_TABLE, columns, KEY_ROWID+"=?", new String[] {"8"}, null, null, null);
try the following code:
Cursor cursor = db.query(DATABASE_TABLE, columns, KEY_ROWID + "=8", null, null, null, null);
or i think that nothing exist in your database at KEY_ID=8 bcoz the CursorIndexOutOfBounds exception comes when the query returns no data.Check if database exists at KEY_ROWID=8

SQLiteDatabase - How to use where clause?

public Cursor fetchTimetable() {
return mDb.query(DATABASE_TABLE_TIMETABLE, new String[] {TIMETABLE_ROWID, TIMETABLE_MODULECODE, TIMETABLE_MODULENAME, TIMETABLE_ROOM, TIMETABLE_LECTURER, TIMETABLE_TIME}, null, null, null, null, null);
}
For example if i wanted TIMETABLE_MODULECODE = 123. How would i do this, i have read its the first null. I have tried this below but still doesnt work
public Cursor fetchTimetable() {
String a = "TIMETABLE_CODE = ADD";
return mDb.query(DATABASE_TABLE_TIMETABLE, new String[] {TIMETABLE_ROWID, TIMETABLE_MODULECODE, TIMETABLE_MODULENAME, TIMETABLE_ROOM, TIMETABLE_LECTURER, TIMETABLE_TIME}, a, null, null, null, null);
}
My working example with where args (it's more clear with using it):
String [] settingsProjection = {
DBContract.Settings._ID,
DBContract.Settings.COLUMN_NAME_USER_ID,
DBContract.Settings.COLUMN_NAME_AUTO_LOGIN
};
String whereClause = DBContract.Settings.COLUMN_NAME_USER_ID+"=?";
String [] whereArgs = {userId.toString()};
Cursor c = db.query(
DBContract.Settings.TABLE_NAME,
settingsProjection,
whereClause,
whereArgs,
null,
null,
null
);
db.query
(
TABLE_NAME,
new String[] { TABLE_ROW_ID, TABLE_ROW_ONE, TABLE_ROW_TWO },
TABLE_ROW_ID + "=" + rowID,
null, null, null, null, null
);
TABLE_ROW_ID + "=" + rowID, here "=" is the where clause
What exactly does "still doesn't work" mean?
The following code should work just fine:
public Cursor fetchTimetable() {
String[] columnNames = new String[] {TIMETABLE_ROWID, TIMETABLE_MODULECODE, TIMETABLE_MODULENAME, TIMETABLE_ROOM, TIMETABLE_LECTURER, TIMETABLE_TIME};
String whereClause = "TIMETABLE_MODULECODE=123";
return mDb.query(DATABASE_TABLE_TIMETABLE, columnNames, whereClause, null, null, null, null);
}
the right syntax is
String[] projection= {column names};
String[] where={"values for where clause"}; //this must be array
public Cursor fetchTimetable() {
return mDb.query(TABLE_NAME, projrction, "columname"+"=?", where, null, null, null);
}
The simple way:
return mDb.rawQuery("SELECT * FROM myTable WHERE column1 = "+ someValue, null);
You can use Use this query:
SQLiteDatabase db = this.getReadableDatabase();
//Cursor cursorr = db.rawQuery(Query, null);
Cursor cursorr = db.rawQuery("select * from " + DATABASE_TABLE_EHS + " where " + TASK_ID + "='" + taskid + "'" , null);
if (cursorr.moveToFirst())
{
do {
// your code like get columns
}
while (cursorr.moveToNext());
}
}
If you're checking against a string value you'll want to wrap the string in quotes like below:
dbHelper.COL_EMAIL +"='"+givenEmail+"'",

Android SQLiteDatabase query with LIKE

I have 3 names, Allakhazam, Beatbox and Cunning in my NAMES Table.
public Cursor fetchNamesByConstraint(String filter) {
mDb.query(true, DATABASE_NAMES_TABLE, new String[] { KEY_ROWID,
KEY_NAME }, KEY_NAME + " LIKE ?",
new String[] { filter }, null, null, null,
null);
return mCursor;
}
I call the function with "A" as the filter, but my cursor is returning a 0 count when it should at least return me a 1. Anyone can see what's wrong with the code?
this statement will return all the records whose keyname equals string specified by string, if you use wild card, then you can get desired results. Like:
mDb.query(true, DATABASE_NAMES_TABLE, new String[] { KEY_ROWID,
KEY_NAME }, KEY_NAME + " LIKE ?",
new String[] { filter+"%" }, null, null, null,
null);
Will Lists all the records starting with word in filter.
mDb.query(true, DATABASE_NAMES_TABLE, new String[] { KEY_ROWID,
KEY_NAME }, KEY_NAME + " LIKE ?",
new String[] {"%"+ filter+ "%" }, null, null, null,
null);
Will Lists all the records containing word in filter.
public java.util.Vector<Products> getsearch(String subcategory,String searchby)
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor = db.query(
TABLE_PRODUCTS,
new String[] { SUBCATEGORY, MAIN_CATEGORY, PRODUCT_ID, PRODUCT_NAME, BRAND, PACKAGE_SIZE, PRICE },
SUBCATEGORY + " LIKE '%" + subcategory + "%'",
null, null, null, null, null);
}
Can you try this.....code.......
public static final String KEY_ROWID="row";
public static final String KEY_NAME="name";
public Cursor fetchNamesByConstraint(String filter) {
Cursor cursor=mDb.query(true, DATABASE_NAMES_TABLE, null,"row LIKE '%"+filter+"%' or name LIKE '%"+filter+"%'",null, null, null, null);
}
You should give the filter with wildcards ;)
"A%"
You can use Raw Queries.
public Cursor fetchNamesByConstraint(String filter) {
String query = "SELECT * FROM " + TABLE_NAME + " WHERE " +
COLUMN_NAME + " LIKE '%" + filter + "%'" ;
SQLiteDatabase db = this.getReadableDatabase();
cursor = db.rawQuery(query, null);
return mCursor;
}
public Cursor fetchNamesByConstraint(String filter) {
mDb.query(true, DATABASE_NAMES_TABLE, new String[] { KEY_ROWID,
KEY_NAME }, KEY_NAME + " LIKE ?",
new String[] {"%"+ filter +"%"}, null, null, null,
null);
return mCursor;
}
The rest is up to our desing, cursor is commanly same
public ArrayList<AboneDataList> getAllPasssiveAboneByDate(String mDate) {
ArrayList<AboneDataList> foodList = new ArrayList<>();
AboneDataList food;
SQLiteDatabase database = dbHelper.getReadableDatabase();
final String kolonlar[] = {DBHelper.COLUMN_A_ID,
DBHelper.COLUMN_A_ABONE_NO,
DBHelper.COLUMN_A_NAME,
DBHelper.COLUMN_A_IS_STUFF,
DBHelper.COLUMN_A_COUNTRY,
DBHelper.COLUMN_A_CITY,
DBHelper.COLUMN_A_TOWN,
DBHelper.COLUMN_A_ADDRESS,
DBHelper.COLUMN_A_PHONE,
DBHelper.COLUMN_A_MOBILE,
DBHelper.COLUMN_A_DATE_START,
DBHelper.COLUMN_A_DATE_END,
DBHelper.COLUMN_A_COUNT,
DBHelper.COLUMN_A_IS_ACTIVE,
DBHelper.COLUMN_A_CARGO,
DBHelper.COLUMN_A_YURT_ID,
DBHelper.COLUMN_A_JOURNAL,
DBHelper.COLUMN_A_MAIL,
DBHelper.COLUMN_A_BUSINESS,
DBHelper.COLUMN_A_BIRTH,
DBHelper.COLUMN_A_GENDER,
DBHelper.COLUMN_A_ABONE_TYPE,
DBHelper.COLUMN_A_MEDENI_TYPE};
//String whereClause = DBHelper.COLUMN_A_JOURNAL + " = ? AND " + DBHelper.COLUMN_A_IS_ACTIVE + " = ? ";
//final String whereArgs[] = {String.valueOf(mJournal),isActive};
//Cursor cursor = database.query(DBHelper.TABLE_ABONE, kolonlar, whereClause, whereArgs,
// null, null, DBHelper.COLUMN_A_ID + " ASC");
Cursor cursor = database.rawQuery("select * from " + DBHelper.TABLE_ABONE + " WHERE "
+ DBHelper.COLUMN_A_DATE_END + " LIKE '%" + mDate + "%'", null);
//Cursor cursor = database.query(DBHelper.TABLE_ABONE, kolonlar, null, null, null, null, DBHelper.COLUMN_A_NAME + " ASC");
while (cursor.moveToNext()) {
food = new AboneDataList();
food.setId(cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_A_ID)));
food.setAbone_no(cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_A_ABONE_NO)));
food.setName(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_A_NAME)));
food.setIs_stuff(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_A_IS_STUFF)));
food.setCountry(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_A_COUNTRY)));
food.setCity(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_A_CITY)));
food.setTown(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_A_TOWN)));
food.setAddress(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_A_ADDRESS)));
food.setPhone(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_A_PHONE)));
food.setMobile(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_A_MOBILE)));
food.setDate_start(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_A_DATE_START)));
food.setDate_end(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_A_DATE_END)));
food.setCount(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_A_COUNT)));
food.setIs_active(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_A_IS_ACTIVE)));
food.setCargo(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_A_CARGO)));
food.setYurt_id(cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_A_YURT_ID)));
food.setJournal(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_A_JOURNAL)));
food.setMail(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_A_MAIL)));
food.setBusiness(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_A_BUSINESS)));
food.setBirth(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_A_BIRTH)));
food.setGender(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_A_GENDER)));
food.setAbone_type(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_A_ABONE_TYPE)));
food.setMedeni_hal(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_A_MEDENI_TYPE)));
foodList.add(food);
}
database.close();
cursor.close();
return foodList;
}

Categories

Resources