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".
Related
I saved data on sqlite db with year and month, now want to retrieve data based on year and month but object is always null.
Here is my code
public List<AddIncomeModel> fetch(String year,String month) {
database = this.getReadableDatabase();
// Cursor cursor = database.query(TABLE_NAME, null, null, null, null, null, null);
Cursor cursor=database.rawQuery("SELECT * FROM " + TABLE_NAME+" WHERE " +YEAR +" = "+year+" AND " + MONTH + " = "+month,null);
List<AddIncomeModel> contacts = new ArrayList<AddIncomeModel>();
AddIncomeModel contactModel;
if (cursor.getCount() > 0) {
for (int i = 0; i < cursor.getCount(); i++) {
cursor.moveToNext();
contactModel = new AddIncomeModel();
contactModel.setId(cursor.getInt(0));
contactModel.setIncome_source(cursor.getString(1));
contactModel.setDescription(cursor.getString(2));
contactModel.setAmount(cursor.getString(3));
contacts.add(contactModel);
}
}
cursor.close();
database.close();
return contacts;
}
Please tell me where I am going wrong.
Thanks
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.
Try Like This
cursor = db.query(TABLE_NAME, new String[] { ID, YEAR , MONTH},
YEAR + " LIKE ? AND " + MONTH+ " LIKE ?",
new String[] {"%" + dan + "%", "%" + vrijeme + "%"},
null, null, null, null);
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));;
}
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.
Cant anyone tell me why I the flowing query isn't working properly?
It suppose to return true if there are types with same name and different _ID(Key)
//****************************************************************************************************//
// ifExistButMy(String typeName,int ID) FUNCTION: return true if type name exists but mine(ID)
//
//****************************************************************************************************//
public boolean ifExistButMy(String typeName,int ID){
Cursor cur;
SQLiteDatabase db = content.getWritableDatabase();
cur = db.query(TABLE_NAME, null,TYPE_NAME + "='" + typeName + "'"+" AND "+ _ID+ " <> " + ID,null, null, null, null);
return cur.moveToFirst(); //returns false if cur is empty
}
String[] mFields=new String[]{"columnName1","columnName2",....}
cur = db.query(TABLE_NAME, mFields,TYPE_NAME + "='" + typeName + "'"+" AND "+ _ID+ " <> " + ID,null, null, null, null);
your second argument is null rather than having which field to be selected
I want to retrieve the contact details along with the group which it belongs to. I got the code to list all the contact groups in the phone.
Cursor groupC = getContentResolver().query(
ContactsContract.Groups.CONTENT_URI, null, null, null, null);
while (groupC.moveToNext()) {
String groupid =
groupC.getString(groupC.getColumnIndex(ContactsContract.Groups._ID));
Log.e("myTag", groupid);
String grouptitle =
groupC .getString(groupC.getColumnIndex(ContactsContract.Groups.TITLE));
Log.e("myTag", grouptitle);
}
groupC.close();
Then I tried to query for a particular contact by using its id but it always shows There is no such column....
Cursor groupC = getContentResolver().query(
ContactsContract.Groups.CONTENT_URI,
null,
ContactsContract.Contacts._ID+"= ?",
new String[]{id},
null);
where id is
Cursor cur = cr.query(
ContactsContract.Contacts.CONTENT_URI,
null,
null,
null,
null);
id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
How to query the group using a particular contact id?
I found the answer.we should pass the raw contact-id and the correct mime type.
String where = ContactsContract.Data.RAW_CONTACT_ID
+ "="
+ Integer.parseInt(id)
+ " AND "
+ ContactsContract.Data.MIMETYPE
+ "='"
+ ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE
+ "'";
Cursor cursor = ctx
.getContentResolver()
.query(ContactsContract.Data.CONTENT_URI, null, where, null,
null);
startManagingCursor(cursor);
Log.e("Count is:", ""+ cursor.getCount());
while (cursor.moveToNext()) {
groupid = cursor
.getString(cursor.getColumnIndex(ContactsContract.Data.DATA1));
Log.e("groupid", groupid);
builder.append(groupid);
}String where = ContactsContract.Data.RAW_CONTACT_ID
+ "="
+ Integer.parseInt(id)
+ " AND "
+ ContactsContract.Data.MIMETYPE
+ "='"
+ ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE
+ "'";
Cursor cursor = ctx
.getContentResolver()
.query(ContactsContract.Data.CONTENT_URI, null, where, null,
null);
startManagingCursor(cursor);
Log.e("Count is:", ""+ cursor.getCount());
while (cursor.moveToNext()) {
groupid = cursor
.getString(cursor.getColumnIndex(ContactsContract.Data.DATA1));
Log.e("groupid", groupid);
break;
}
A contact may be in more than one group,here it retrivr its first group pnly.
I think this may be useful to somebody...