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);
Related
I have a function which takes in a month and year parameter and returns all values from the DB where month and year match, now I need to make a query to the db where year matches a variable but month can be any month, i want to use the same function rather than create a new function, so with what values do I call this function.
Current call looks like this
ArrayList<PaymentHistory> allPayment = dataSource.findfiltered("Transactions", yearToGet, monthToGet);
and then function looks like this
public ArrayList<PaymentHistory> findfiltered(String dbName, String year, String month){
//this needs to be done still
String whereClause = DBOpenHelper.YEAR + " = ? AND "+ DBOpenHelper.STATUS + " = ? AND " + DBOpenHelper.MONTH + " = ?";
String[] whereArgs = new String[] {
year,
"paid", //we only want successful transactions
month
};
Cursor cursor = database.query(dbName, allColumns, whereClause, whereArgs, null, null, null); //must sort this
ArrayList<PaymentHistory> paymentHistories = getListDatas(cursor);
cursor.close();
return paymentHistories;
}
Make the following changes in your method.
public ArrayList<PaymentHistory> findfiltered(String dbName, String year, String month){
//this needs to be done still
String whereClause = DBOpenHelper.YEAR + " = ? AND "+ DBOpenHelper.STATUS + " = ? AND " + DBOpenHelper.MONTH + " = ?";
String[] whereArgs = new String[] {
year,
"paid", //we only want successful transactions
month
};
if(month == null) {
whereClause = DBOpenHelper.YEAR + " = ? AND "+ DBOpenHelper.STATUS + " = ?";
String[] whereArgs = new String[] {
year,
"paid"
};
}
Cursor cursor = database.query(dbName, allColumns, whereClause, whereArgs, null, null, null); //must sort this
ArrayList<PaymentHistory> paymentHistories = getListDatas(cursor);
cursor.close();
return paymentHistories;
}
Now when you need to get result regardless of the month, just pass a null at month's place.
ArrayList<PaymentHistory> allPayment = dataSource.findfiltered("Transactions", yearToGet, null);
If need filter by month, call
ArrayList<PaymentHistory> allPayment = dataSource.findfiltered("Transactions", yearToGet, monthToGet);
If do not need filter by month, call
ArrayList<PaymentHistory> allPayment = dataSource.findfiltered("Transactions", yearToGet, "");
Method:
public ArrayList<PaymentHistory> findfiltered(String dbName, String year, String month){
//this needs to be done still
String whereClause = DBOpenHelper.YEAR + " = ? AND "+ DBOpenHelper.STATUS + " = ?";
Cursor cursor = null;
if(month != "")
{
whereClause +=" AND " + DBOpenHelper.MONTH + " = ?";
cursor = database.query(dbName, allColumns, whereClause, new String[] {year,"paid",month}, null, null, null); //must sort this
}
else{
cursor = database.query(dbName, allColumns, whereClause, new String[] {year,"paid"}, null, null, null); //must sort this
}
ArrayList<PaymentHistory> paymentHistories = getListDatas(cursor);
cursor.close();
return paymentHistories;
}
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".
I'm creating a contact app in android and I'm adding contacts to a specific account. How can I select all Data rows for all RawContacts belonging to this account in one query?
I know I can first select all RawContacts belonging to the account and then foreach _ID I could select all Data entries. But first of all that's really slow, but most important I want to get a cursor for all those Data rows so that I can provide this cursor to a CursorAdapter.
Cursor rawCursor = context.getContentResolver().query(
RawContacts.CONTENT_URI,
new String[] {
RawContacts.CONTACT_ID,
RawContacts._ID,
},
RawContacts.ACCOUNT_TYPE + " = ? AND " + RawContacts.ACCOUNT_NAME + " = ? ",
new String[] {account_type, account_name},
null);
while (rawCursor.moveToNext()) {
long rawContactID = rawCursor.getLong(rawCursor.getColumnIndex(RawContacts._ID));
Cursor dataCursor = mContext.getContentResolver().query(
Data.CONTENT_URI,
new String[] {
Data._ID,
Data.MIMETYPE,
Data.IS_SUPER_PRIMARY,
Data.DATA1,
Data.DATA2,
Data.DATA3,
},
Data.RAW_CONTACT_ID + " = ?",
new String[] {String.valueOf(rawContactID)},
null);
}
For now I solved this by first querying all raw_contacts and then using an IN statement in the selection. like:
ArrayList<String> ids = new ArrayList<String>();
Cursor idCursor = getRawContactsCursor(context, new String[]{RawContacts._ID}, account_name);
try {
while (idCursor.moveToNext()) {
ids.add(idCursor.getString(idCursor.getColumnIndex(RawContacts._ID)));
}
} finally {
idCursor.close();
}
String idSql = "?";
for (int i = 1; i < ids.size(); i++) {
idSql += ",?";
}
String whereSQL = Data.RAW_CONTACT_ID + " IN (" + idSql + ")";
String[] whereArgs = null;
if (!TextUtils.isEmpty(mimetype)) {
whereSQL += " AND " + Data.MIMETYPE + " = ? ";
ids.add(mimetype);
}
whereArgs = ids.toArray(new String[ids.size()]);
Cursor cursor = context.getContentResolver().query(
Data.CONTENT_URI,
projection,
whereSQL,
whereArgs,
Data.RAW_CONTACT_ID);
return cursor;
I just wonder what will happen when the number of raw_contacts becomes large enough. I'm guessing that having a thousand or more raw_contact id's will break stuff.
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);
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Fetch data in database table insert it if not exist else return the row id
I try to fetch if data exist in database table, if yes I should get the row id else I insert it in the table this my code
public int finddate(String date){
int id=0;
AndroidOpenDbHelper androidOpenDbHelperObj = new AndroidOpenDbHelper(this);
SQLiteDatabase sqliteDatabase = androidOpenDbHelperObj.getWritableDatabase();
Cursor cursor = sqliteDatabase.rawQuery("SELECT _id FROM " +
AndroidOpenDbHelper.TABLE_DATE + " where " +
AndroidOpenDbHelper.COLUMN_NAME_DATE + " = " + date,
null);
startManagingCursor(cursor);
if (cursor != null) {
if( cursor.moveToFirst() ) {
id = cursor.getInt(cursor.getColumnIndex("_id"));
}
} else {
id=0;
}
sqliteDatabase.close();
return id;
}
when i try with an existing item I get the result of this method =0 and the item is inserted in the table,
how can I do this?
The date is not being correctly escaped. The safest and cleanest way to resolve it is to pass the date value as a parameter, rather than embedding it in the query.
You can also tidy up the cursor management quite a bit. You don't need to check for a null cursor, as an exception will be thrown if the query fails. Also, you don't need to set id = 0 as you've already done that at the start. This is much simpler:
Cursor cursor = sqliteDatabase.rawQuery("SELECT _id FROM " +
AndroidOpenDbHelper.TABLE_DATE + " where " +
AndroidOpenDbHelper.COLUMN_NAME_DATE + " = ?",
new String[] { date } );
if ( cursor.moveToFirst() ) {
id = cursor.getInt(cursor.getColumnIndex("_id"));
}
cursor.close();
sqliteDatabase.close();
Your query should look like this:
Cursor cursor = sqliteDatabase.rawQuery("SELECT _id FROM " + AndroidOpenDbHelper.TABLE_DATE + " where "+ AndroidOpenDbHelper.COLUMN_NAME_DATE+ " =\'"+date+"\'", null);
startManagingCursor(cursor);
cursor.moveTofirst();
if (cursor.getCount() > 0) {
id = cursor.getInt(cursor.getColumnIndex("_id"));
}
} else {
id=0;
}