Selection Statements in Android SQLite - android

I have a database table with several columns in it. I want to select certain rows by comparing a string entered by a user and select records based on their entry. I have the following code:
SearchbyIngredient.Java
final Button searchbutton1 = (Button) findViewById(R.id.searchbutton1);
searchbutton1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Cursor temp = dbIngredientHelper.getDrinks(textView.getText().toString());
String ingred = temp.getString(0);
Context context = getApplicationContext();
iadapter = new IngredientAdapter(temp);
myListView.setAdapter(iadapter);
}
});
}
IngredientHelper.Java
public Cursor getDrinks(String drinkName) throws SQLException{
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(TABLE_NAME2);
String selection = COLUMN_INGRED1 + "= ' " + drinkName + "'";
String[] asColumnsToReturn = new String[] { COLUMN_ID2, COLUMN_DRINKNAME, COLUMN_INGRED1, COLUMN_AMT1, COLUMN_INGRED2, COLUMN_AMT2, COLUMN_INGRED3, COLUMN_AMT3, COLUMN_INGRED4, COLUMN_AMT4 };
Cursor mCursor2 = queryBuilder.query(dbSqlite, asColumnsToReturn, selection, null, null, null, COLUMN_DRINKNAME);
/*Cursor mCursor = dbSqlite.query(true, TABLE_NAME2, new String[]{
COLUMN_DRINKNAME},
COLUMN_INGRED1 + "= ' " + drinkName + "'", null, null, null, null, null);
if (mCursor != null){
mCursor.moveToFirst();
}*/
mCursor2.moveToFirst();
return mCursor2;
}
My question is regarding
String selection = COLUMN_INGRED1 + "= ' " + drinkName + "'";
This code currently works, however it only finds entries with the user's text in COLUMN_INGRED1 (only a single column in the code). How can I format the statement or make a series of statements so that it also looks for the user's text in COLUMN_INGRED2, COLUMN_INGRED3 and COLUMN_INGRED4? Thank you

Standard SQL applies, use an OR:
COLUMN_INGRED1 + "= ' " + drinkName + "' OR " COLUMN_INGRED2 + "= '" +drinkName + "'" ...;
Note that = will do an exact match, you might want to look into the LIKE operator.

Related

Android search contacts by phone number and contact name (Both in same time)

I want to query on contacts by phone number and contact name in same time with "LIKE" operator, here is my code :
ContentResolver contentResolver = context.getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1 AND (" + ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " LIKE '" + query + "%' OR " + ContactsContract.CommonDataKinds.Phone.NUMBER + " LIKE '%" + query + "%' OR " + ContactsContract.CommonDataKinds.Phone.NUMBER + " LIKE '%" + query + "%' ) ", null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
return cursor;
But my code does not work, it's crashes and android says "data4" and "data1" column does not exist.
Use below code to find contact by name
public String findByName(Context context , String name) {
String result= null;
String selection = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" like'%" + name +"%'";
String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor c = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection, selection, null, null);
if (c.moveToFirst()) {
result= c.getString(0);
}
c.close();
if(result==null)
result= "This contact is not saved into your device";
return result;
}
Use loader to get fastest results.
public Loader<Cursor> getContactCursor(Context context, Bundle args) {
Uri baseUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String filter = args != null ? args.getString("filter") : null;
if (filter != null && filter.length() > 0) {
return new CursorLoader(context,baseUri, null, "(display_name LIKE ?) OR (data1 LIKE ?)", new String[]{"%" + filter + "%","%" + filter + "%"}, null);
}else{
return new CursorLoader(context,baseUri, projection,null, null, null);
}
}

How to query a SQLite database

This is my table:
private static final String CREATE_TABLE_EMPLOYEES = "CREATE TABLE "+ TABLENAME + "(" +
COLUMNS[0] + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , " +
COLUMNS[1] + " TEXT NOT NULL , " +
COLUMNS[2] + " TEXT NOT NULL , " +
COLUMNS[3] + " TEXT NOT NULL , " +
COLUMNS[4] + " TEXT NOT NULL , " +
COLUMNS[5] + " TEXT NOT NULL " +
");";
And query all data from database:
public List<Employee> getEmployees() {
List<Employee> employees = new ArrayList<Employee>();
Cursor cur = db.query(dbHelper.TABLENAME, columns, null, null, null, null, null);
cur.moveToFirst(); // need to start the cursor first...!
while(!cur.isAfterLast()) { // while not end of data stored in table...
Employee emp = new Employee();
emp.setId(cur.getInt(0));
emp.setName(cur.getString(1));
emp.setCharge(cur.getString(2));
emp.setDepartament(cur.getString(3));
emp.setPhone(cur.getString(4));
emp.setEmail(cur.getString(5));
employees.add(emp);
cur.moveToNext(); // next loop
}
cur.close(); // !important
return employees;
}
I want to query all data if employee name =="ali"
Please help me.
I want to query all data if employee name =="ali".
3rd and 4th parameter is available in query method for adding WHERE clause in query.
Do it as:
Cursor cur = db.query(dbHelper.TABLENAME, columns,
"name=?",
new String[] { "ali" },
null, null, null);
Try this, this will also help you prevent from sql injection
Cursor cur = db.query(dbHelper.TABLENAME, columns, columns[1]+" = ?", new String[]{"ali"}, null, null, null);
Replace
Cursor cur = db.query(dbHelper.TABLENAME, columns, null, null, null, null, null);
with
Cursor cur = db.query(dbHelper.TABLENAME, columns, columns[1]+" = ?", new String[]{"ali"}, null, null, null);
The 3rd parameter in db.query() method is "selection statement"
and the 4th parameter is "selection arguments".
Use this cursor to query all data if employee name =="ali":-
String selection = COLUMNS[x] + " = " + "'" + ali + "'";
Cursor cur = db.query(dbHelper.TABLENAME, columns, selection, null, null, null, null);
Here COLUMNS[x] should be the column containing the employee names and "x" be the respective column number.
This cursor will fetch you only the records/tuples for the employee named "ali".

How to get data from SQLite databse in Android

I want to get some data from my database I have created using my application. Here is my code
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.select_to_delete);
database = new DatabaseHandler(this);
bundle = getIntent().getExtras();
date = bundle.getString("DATE");
SQLiteDatabase db=database.getWritableDatabase();
Cursor cur=db.rawQuery("SELECT " +TITLE+ " FROM " +TABLE_NAME + " WHERE " + CDATE + "=" + date,null);
int i = cur.getCount();
if(cur !=null){
if (cur.moveToFirst()){
do{
tdate = cur.getString(cur.getColumnIndex("DATE"));
titlearray.add(tdate);
}while(cur.moveToNext());
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, titlearray);
ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(adapter);
}
My table has 5 columns (id, title, date, time, descrption). and have 4 raws. The table is created in another class.
When I run this application it doesn't get the data from the sql table and show it in listview. When I debug it, it shows i=1 and the it returns false to if (cur.moveToFirst()). So it doesn't go inside that if part.
What could my mistake be?
place apostrophe (') around your date
Cursor cur=db.rawQuery("SELECT " +TITLE+ " FROM " +TABLE_NAME + " WHERE " + CDATE + "='" + date+"'",null);
N.B. I am assuming your table creation and other field names are accurate. Also recheck those
Use selection args and you will be avoiding tons of problems:
Cursor cur=db.rawQuery("SELECT " +TITLE+ " FROM " +TABLE_NAME + " WHERE " + CDATE + " = ?", new String[] { date });
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[] { TITLE}, CDATE + "=?",
new String[] { String.valueOf(date) }, null, null, null, null);
if (cursor.moveToFirst()) {
do {
//add to the array
} while (cursor.moveToNext());
}

Android SQLite Query Where and Where

I need to return the ID value from the database where dan == table_column_one and where vrijeme == table_column_two. I don't know how to do this.
public static int returnID(String dan, int vrijeme){
Cursor cursor;
int IDRQ;
cursor = db.query
(
TABLE_NAME,
new String[] { TABLE_COLUMN_ID, TABLE_COLUMN_ONE, TABLE_COLUMN_TWO },
new String[] {TABLE_COLUMN_ONE + " like " + "'%" + dan + "%'", TABLE_COLUMN_TWO + " like " + "'%" + vrijeme + "%'"}, null, null, null, null
);
cursor.moveToFirst();
IDRQ = cursor.getInt(0);
return IDRQ;
} );
This is how I tried, but of course, its wrong.
In SQLiteDatabase.query() the selection comes in two parts. The where clause (a String) and the whereArgs (an array of String).
To add more than one condition to the where clause you can use AND or OR, just like && or || in Java.
A question mark in the where clause is bound to one of the Strings in the whereArgs array.
cursor = db.query(TABLE_NAME, new String[] { TABLE_COLUMN_ID, TABLE_COLUMN_ONE, TABLE_COLUMN_TWO },
TABLE_COLUMN_ONE + " LIKE ? AND " + TABLE_COLUMN_TWO + " LIKE ?",
new String[] {"%" + dan + "%", "%" + vrijeme + "%"},
null, null, null, null);

Android SQLite Query: Trouble with WHERE clause

Please let me know why my where clause isn't working. I tried using the query instead of rawquery but no luck.
try {
String categoryex = "NAME";
DBHelper dbHelper = new DBHelper(this.getApplicationContext());
MyData = dbHelper.getWritableDatabase();
Cursor c = MyData.rawQuery("SELECT * FROM " + tableName + where Category = '+categoryex'" , null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String firstName = c.getString(c.getColumnIndex("Category"));
String age = c.getString(c.getColumnIndex("Text_Data"));
results.add( firstName + " Directions: " + age);
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (MyData != null)
MyData.execSQL("DELETE FROM " + tableName);
MyData.close();
}
try... (you left out a double-quote before where.
Cursor c = MyData.rawQuery("SELECT * FROM " + tableName + " where Category = '" +categoryex + "'" , null);
I think you should use rawQuery in this form:
rawQuery("SELECT * FROM ? where Category = ?", new String[] {tableName, categoryex});
I think it's more secure this way.
Your quotes are buggered:
Cursor c = MyData.rawQuery("SELECT * FROM " + tableName + " where Category = '" + categoryex + "'" , null);
You also should read up on SQL injection attacks.
it will be more easy if you use this technique instead of rawQuery,its easy way change your table name, columns and where conditions accordingly.
public ArrayList<Invitees> getGroupMembers(String group_name) {
ArrayList<Invitees> contacts = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
String[] projection = {COLUMN_CONTACT, COLUMN_PHONE_NUMBER};
String selection = COLUMN_GROUP_NAME + "=?";
String[] selectionArgs = {group_name};
Cursor cursor = db.query(GROUPS_TABLE_NAME, projection, selection, selectionArgs, null, null, null);
if (cursor.moveToFirst()) {
do {
Invitees invitees = new Invitees();
invitees.setUserName(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_CONTACT)));
invitees.setInviteePhone(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_PHONE_NUMBER)));
contacts.add(invitees);
} while (cursor.moveToNext());
}
return contacts;
}

Categories

Resources