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;
}
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 have a TextView to which I'm putting my contacts which have birthdays:
private String loadContacts()
{
StringBuilder builder = new StringBuilder();
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null,
null, null);
if (cursor.getCount() > 0){
while (cursor.moveToNext()){
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String columns[] = {
ContactsContract.CommonDataKinds.Event.START_DATE,
ContactsContract.CommonDataKinds.Event.TYPE,
ContactsContract.CommonDataKinds.Event.MIMETYPE,
};
String where = ContactsContract.CommonDataKinds.Event.TYPE + "=" +
ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY +
" and " + ContactsContract.CommonDataKinds.Event.MIMETYPE +
" = '" + ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE +
"' and " + ContactsContract.Data.CONTACT_ID + " = " + id;
String sortOrder = ContactsContract.CommonDataKinds.Event.START_DATE + " ASC";
Cursor birthdayCur = cr.query(ContactsContract.Data.CONTENT_URI, columns, where,
null, sortOrder);
if (birthdayCur.getCount() > 0) {
while (birthdayCur.moveToNext()) {
String birthday = birthdayCur.getString(birthdayCur.
getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
builder.append("Contact: ").append(name).append(" ").append(birthday).append("\n\n");
}
}
birthdayCur.close();
}
}
cursor.close();
return builder.toString();
}
And then assign the contacts on the "onCreate" function
if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.READ_CONTACTS }, 1);
} else {
listContacts.setText(loadContacts());
}
This line of code:
String sortOrder = ContactsContract.CommonDataKinds.Event.START_DATE + " ASC";
Cursor birthdayCur = cr.query(ContactsContract.Data.CONTENT_URI, columns, where,
null, sortOrder);
doesn't seem to work no matter what I put there to order it (name, _ID etc.).
I am trying to sort by Birthdays but even if I try to sort by name it doesn't work. Why ?
Am I using wrong type of View(TextView) or is it the way I use StringBuilder to set the text or something else entirely?
My minSdkVersion is 19 and targetSdkVersion 26. I'm testing this App on my Nexus5(api 23 android 6.01) on debugging mode.
I appreciate any advice.
Well this is what happens when I hurried. It was actually beyond simple.
I just needed to put all my needed columns in the first Cursor and the second more important thing was to use "ContactsContract.Data.CONTENT_URI"
instead of "ContactsContract.Contacts.CONTENT_URI" because the "DATA.CONTENT_URI" actually has all of my needed columns and "Contacts.CONTENT_URI" doesn't.
As simple as that.
private String loadContacts()
{
StringBuilder builder = new StringBuilder();
ContentResolver cr = getContentResolver();
String columns[] = {
ContactsContract.CommonDataKinds.Event.START_DATE,
ContactsContract.Contacts.DISPLAY_NAME
};
String where = ContactsContract.CommonDataKinds.Event.TYPE + "=" +
ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY +
" and " + ContactsContract.CommonDataKinds.Event.MIMETYPE +
" = '" + ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE + "'";
String sortOrder = ContactsContract.CommonDataKinds.Event.START_DATE + " ASC";
Cursor cursor = cr.query(ContactsContract.Data.CONTENT_URI,
columns, where,
null, sortOrder);
if (cursor.getCount() > 0){
while (cursor.moveToNext()){
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String birthday = cursor.getString(cursor.
getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
builder.append("Contact: ").append(name).append(birthday).append(" ").append("\n\n");
}
}
cursor.close();
return builder.toString();
}
hey I am unable to get the call type == missed call and of current date only.
Its can be achieved from Cursor query i have tried this but getting Calls type as missed call
I am using this in onCreate method but not getting any value in logcat????
Here is my piece of code any help would be greatly appreciated......thanks in advance
String where = CallLog.Calls.TYPE+"="+CallLog.Calls.MISSED_TYPE;
int missedtype=CallLog.Calls.MISSED_TYPE;
String missed=Integer.toString(missedtype);
String timestamp = String.valueOf(getTodayTimestamp());
Cursor cursor = this.getContentResolver()
.query(CallLog.Calls.CONTENT_URI,
new String[] { CallLog.Calls.DATE, CallLog.Calls.TYPE,
CallLog.Calls.DURATION, CallLog.Calls.NUMBER,
CallLog.Calls._ID },
CallLog.Calls.DATE + ">?" + " and "
+ CallLog.Calls.TYPE + "=?",
new String[] { timestamp, String.valueOf(CallLog.Calls.MISSED_TYPE) },
CallLog.Calls.DATE);
//Cursor managedCursor = this.getContentResolver().query(CallLog.Calls.CONTENT_URI, null, CallLog.Calls.DATE + ">= ?", new String[]{timestamp}, null);
//Cursor cursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI, null, where , null, CallLog.Calls.DATE+ " >= ?");
int number = cursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = cursor.getColumnIndex(CallLog.Calls.TYPE);
int date = cursor.getColumnIndex(CallLog.Calls.DATE);
int duration = cursor.getColumnIndex(CallLog.Calls.DURATION);
{
while (cursor.moveToNext()) {
String LogphNumber = cursor.getString(number);
String callType = cursor.getString(type);
String callDate = cursor.getString(date);
Date callDayTime = new Date(Long.valueOf(callDate));
String callDuration = cursor.getString(duration);
{
if(cursor.getCount()>1){
System.out.println("Total Logs::>>>>>>>>> "+cursor.getCount());
System.out.println("\nPhoneNo:----"+LogphNumber);
System.out.println("\nCallDate: "+callDayTime);
System.out.println("\nCallDuration in Seconds :"+callDuration);
System.out.println("\n-----------------------");
}else if(cursor.getCount()==0){
System.out.println("No Missed calls");
}
}
}cursor.close();
}
try this:
String timestamp = String.valueOf(getTodayTimestamp());
Cursor cursor = this.getContentResolver()
.query(CallLog.Calls.CONTENT_URI,
new String[] { CallLog.Calls.DATE, CallLog.Calls.TYPE,
CallLog.Calls.DURATION, CallLog.Calls.NUMBER,
CallLog.Calls._ID },
CallLog.Calls.DATE + ">?" + " and "
+ CallLog.Calls.TYPE + "=?",
new String[] { timestamp, String.valueOf(CallLog.Calls.MISSED_TYPE) },
CallLog.Calls.DATE);
I'm executing the following method with no success beacause of the selectArgs being incorrect (at least this is what I believe.
findAll:
public Collection<Object> findAllByCodigoSetorOrderByStatusWhereDataAgendamentoIsNull(Integer vendedor) {
Collection<Object> objects = null;
String selection = Object.FIELDS[20] + "=?" + " OR " + Object.FIELDS[20] + "=?" + " OR " + Object.FIELDS[20] + "=?" + " AND " + Object.FIELDS[6] + "=?";
String[] selectionArgs = new String[] { "''", "'null'", "NULL", String.valueOf(vendedor) };
Collection<ContentValues> results = findAllObjects(Object.TABLE_NAME, selection, selectionArgs, Object.FIELDS, null, null, Object.FIELDS[4]);
objects = new ArrayList<Object>();
for (ContentValues result : results) {
objects.add(new Object(result));
}
return objects;
}
findAllObjects:
protected Collection<ContentValues> findAllObjects(String table, String selection, String[] selectionArgs, String[] columns, String groupBy, String having, String orderBy) {
Cursor cursor = null;
ContentValues contentValue = null;
Collection<ContentValues> contentValues = null;
try {
db = openRead(this.helper);
if (db != null) {
cursor = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
contentValues = new ArrayList<ContentValues>();
for (int i = 0; i < cursor.getCount(); i++) {
cursor.moveToPosition(i);
contentValue = new ContentValues();
for (int c = 0; c < cursor.getColumnCount(); c++) {
contentValue.put(cursor.getColumnName(c), cursor.getString(c));
}
contentValues.add(contentValue);
cursor.moveToNext();
}
}
return contentValues;
} finally {
close(db);
}
}
How can I correctly select and compare a column to - null, 'null' and '' using the db.query?
Android's database API does not allow to pass NULL values as parameters; it allows only strings.
(This is a horrible design bug. Even worse, SQLiteStatement does allow all types for parameters, but works only for queries that return a single value.)
You have no choice but to change the query string to blah IS NULL.
Old question but i was still stuck on this for a few hours until i found this answer. For whatever reason this strange behaviour (or bug) still exists within the android sdk, if you want to query against null values simply do
SQLiteDatabase db = getReadableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("columnName", newValue);
String nullSelection = "columnName" + " IS NULL";
db.update("tableName", contentValues, nullSelection, null);
db.close();
In this example i am updating values, but it is a similar concept when just selecting values
As mentioned in other answers, for null "IS NULL" need to be used. Here is some convenience code for having both null and strings (I'm using delete in the example but the same can be done for other methods, e.g. query):
public void deleteSomething(String param1, String param2, String param3) {
ArrayList<String> queryParams = new ArrayList<>();
mDb.delete(TABLE_NAME,
COLUMN_A + getNullSafeComparison(param1, queryParams) + "AND " +
COLUMN_B + getNullSafeComparison(param2, queryParams) + "AND " +
COLUMN_C + getNullSafeComparison(param3, queryParams),
queryParams.toArray(new String[0]));
}
private String getNullSafeComparison(String param, List<String> queryParams) {
if (param == null) {
return " IS NULL ";
} else {
queryParams.add(param);
return " = ? ";
}
}
You can bind NULL values to SQLiteStatement:
SQLiteDatabase db = getWritableDatabase();
SQLiteStatement stmt = db.compileStatement("UPDATE table SET " +
"parameter=? WHERE id=?");
if (param == null)
stmt.bindNull(1);
else
stmt.bindString(1, param);
stmt.execute();
stmt.close();
db.close();
public String getContact(String searchName) {
SQLiteDatabase db = this.getReadableDatabase();
String[] args = { searchName };
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_MOVIES
+ " WHERE name =? ", args);
String iName = null, iDiretor = null, iGenre = null;
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
iName = cursor.getString(cursor.getColumnIndex(KEY_NAME));
iDiretor = cursor.getString(cursor.getColumnIndex(KEY_DIRECTOR));
iGenre = cursor.getString(cursor.getColumnIndex(KEY_GENRE));
cursor.moveToNext();
}
cursor.close();
The iName variable is working fine but the other two are returning null. Any help?
Use the SQLiteDatabase query methods instead of rawQuery for the best results.
db.query(TABLE_MOVIES, null, "name = ?", args, null);
This is preferred because rawQuery is easy to mess up and doesn't protect against SQL injections.
Try this way:
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_MOVIES + " WHERE name LIKE ? ", args);
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_MOVIES
+ " WHERE name LIKE "+searchName, null); // Put Like When your are comparing String