Android SQLiteDatabase query with LIKE - android

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

Related

How use query() with WHERE clause?

I need to get the question, where the column : activity, lesson and screen are equal to eg: " 1", " 2" , "3".
Note: question is a column too.
My code should return a string = "4" but are returning:
android.database.sqlite.SQLiteCursor#547e1a74
Code:
databaseHelper = Database.getInstance(getApplicationContext());
long id4 = databaseHelper4.insertData("1", "2", "3","4", "5", "6", "7", "8");
String question = databaseHelper4.getQuestion("1", "2", "2");
Message.message(IntroActivity.this, question);
Database:
public String getQuestion(String activity, String lesson, String screen){
SQLiteDatabase db = helper.getWritableDatabase();
String[] columns = {DatabaseHelper.QUESTION};
Cursor cursor = db.query(DatabaseHelper.TABLE_NAME, columns, DatabaseHelper.ACTIVITY +
"=?" + " AND " + DatabaseHelper.LESSON + "=?" + " AND " + DatabaseHelper.SCREEN +
"=?", new String[]{activity, lesson, screen}, null, null, null, null);
return cursor.toString();
}
Here:
return cursor.toString();
Cursor.toString() method return String representation of Cursor instead of values which is contained by Cursor.
Get QUESTION Column value from cursor as:
cursor.moveToFirst();
String question = cursor.getString(cursor.getColumnIndex(
DatabaseHelper.QUESTION));
instead of returning cursor.toString(), you should return
cursor.getString(cursor.getColumnIndex(DatabaseHelper.QUESTION));
after you call cursor.moveToFirst();
public String getQuestion(String activity, String lesson, String screen){
SQLiteDatabase db = helper.getWritableDatabase();
String[] columns = {DatabaseHelper.QUESTION};
Cursor cursor = db.query(DatabaseHelper.TABLE_NAME, columns, DatabaseHelper.ACTIVITY +
"=?" + " AND " + DatabaseHelper.LESSON + "=?" + " AND " + DatabaseHelper.SCREEN +
"=?", new String[]{activity, lesson, screen}, null, null, null, null);
cursor.moveToFirst()
return cursor.getString(cursor.getColumnIndex(DatabaseHelper.QUESTION));;
}

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.

Setting multiple Selections args in SQLite database query

How would i go about querying more than one selection arg? For example here is how my database is formatted
Here is the code i used to search with just one seletion arg:
public Cursor getType(String type) throws SQLException
{
Cursor mCursor =
db.query(true, DB_TABLE, new String[] {
KEY_ROWID,
KEY_ALCOHOL,
KEY_TYPE,
KEY_BRAND,
KEY_PRICE
},
KEY_TYPE + "=?",
new String[] { type },
null,
null,
null,
null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
But this only searches by KEY_TYPE, how would I set it so it searches by KEY_TYPE, KEY_ALCOHOL, and KEY_PRICE?
This may help you
public Cursor getType(String type) throws SQLException
{
Cursor mCursor =
db.query(true, DB_TABLE, new String[] {
KEY_ROWID,
KEY_ALCOHOL,
KEY_TYPE,
KEY_BRAND,
KEY_PRICE
},
KEY_TYPE + "=?" + " AND " + KEY_ALCOHOL + "=?" " AND " + KEY_PRICE + "=?",
new String[] { type,alcohol,price },
null,
null,
null,
null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
Figured it out!! Thanks to #Rajendra for giving me some code to build off of! You can only add Strings into the selections args so i did this:
public Cursor getTest(String alcohol, String type, long price) throws SQLException
{
Cursor mCursor =
myDataBase.query(true, DB_TABLE, new String[] {
KEY_ROWID,
KEY_ALCOHOL,
KEY_TYPE,
KEY_BRAND,
KEY_PRICE
},
KEY_ALCOHOL + "=?" + " AND " + KEY_TYPE + "=?" + " AND " + KEY_PRICE + "<=" + price,
new String[] { alcohol, type},
null,
null,
null,
null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
And it works!!

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+"'",

Categories

Resources