How use query() with WHERE clause? - android

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

Related

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

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

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

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