SQL Between operation in android sqlite date is not working? - android

I am new to android development. I been working on this for one day and i couldn't figure out whats the exact problem is because my query is running without error but no result.
My database query Value of formattedDate
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = df.format(c.getTime());
public Cursor paymentWeek(Activity activity)
{
String[] from = { _PAYMENTID, NAME, REQUESTEDDATE, FROMAD, TOADD, EMAILBODYPAYMENT, AMOUNT};
SQLiteDatabase db = getReadableDatabase();
String orderby = REQUESTEDDATE+" DESC";
Cursor cursor = db.rawQuery("SELECT * FROM " + PAYMENTTABLE+ " WHERE " + REQUESTEDDATE + " BETWEEN date('"+formattedDate+"') AND date('"+formattedDate+"','-7 days')", null);
activity.startManagingCursor(cursor);
return cursor;
}
My database date type is TEXT. i am storing in the format of (yyyy-mm-dd),eg:2012-04-07
But the problem is i can retrieve all datas from the database but if i want to retrieve values for last 7 days it doesn't show any values.
It would be great if any alternatives available? and tip how to go for it?
Thanks...

Cursor cursor = db.rawQuery("SELECT * FROM " + PAYMENTTABLE+ " WHERE " + REQUESTEDDATE + " BETWEEN date('"+formattedDate+"') AND date('"+formattedDate+"-7')", null);
Try out this query, you have made a mistake in date('"+formattedDate+"','-7 days')".

as you say, your date type is TEXT, i dont think you can use between x and y to make the filter to return the content from x to y .
you can try this: http://www.roseindia.net/sql/sql-between-date.shtml or http://www.techonthenet.com/sql/between.php .

Related

Android SQLite rawquery with Date String in WHERE clause not working

I want to get all data if today date is in
between two dates that i have already stored in the table as strings in (in yyyy-MM-dd format).
I tried several ways but nothing worked out.
If i try this in following way it is working fine and receiving correct values.(count = 4)
public int getMedicineDataFromDate() {
SQLiteDatabase db = this.getReadableDatabase();
String dates = "'2018-11-26'";
String stext = "SELECT * FROM " + MED_TABLE_NAME + " WHERE " + dates + " BETWEEN STARTING_DATE AND ENDING_DATE";
#SuppressLint("Recycle") Cursor cursor = db.rawQuery(stext, null);
return cursor.getCount();
}
But what i want to do this by passing date from my activity
as in following way.And this way i get empty cursor (count = 0).
Inside my activity
Date today = Calendar.getInstance().getTime();
SimpleDateFormat e = new SimpleDateFormat("yyyy-MM-dd");
String todayString = e.format(today);
int result = mydb.getMedicineDataFromDate(todayString);
String resl = Integer.toString(result);
Toast.makeText(MainActivity.this,"Data received " + resl,Toast.LENGTH_LONG).show();
In DatabaseHelper class
public int getMedicineDataFromDate(String date) {
SQLiteDatabase db = this.getReadableDatabase();
String stext = "SELECT * FROM " + MED_TABLE_NAME + " WHERE " + date + " BETWEEN STARTING_DATE AND ENDING_DATE";
#SuppressLint("Recycle") Cursor cursor = db.rawQuery(stext, null);
return cursor.getCount();
}
If someone can explain me why i am getting 0 as the count in second way and what is the correct
way to do this.it will be very helpful to me.
I think problem is there.
SimpleDateFormat e = new SimpleDateFormat("yyyy-MM-dd");
String todayString = e.format(today);
You change todayString value as String like
String todayString ="'"+e.format(today)+"'";
this.
Your issue is that you have not enclosed the String in single quotes and therefore it is interpreted as if it is numeric and thus a calculation.
That is the resultant SQL (assuming the date is 2018-11-26 which mathematically is 2018 minus 11 minus 26 = 1981) would be :-
SELECT * FROM your_table WHERE 1981 BETWEEN STARTING_DATE AND ENDING_DATE
You could change String todayString = e.format(today); to be String todayString = "'" + e.format(today) + "'";
Or you could use :-
String stext = "SELECT * FROM " + MED_TABLE_NAME + " WHERE ? BETWEEN STARTING_DATE AND ENDING_DATE";
Cursor cursor = db.rawQuery(stext, new String[]{date}); //<<<<<<<<<< will place quotes around the string for you
Or you could use :-
public int getMedicineDataFromDate(String date) {
SQLiteDatabase db = this.getReadableDatabase();
String whereclause = "? BETWEEN STARTING_DATE AND ENDING_DATE";
String[] whereargs = new String[]{date};
Cursor cursor = db.query(MED_TABLE_NAME,null,whereclause,whereargs,null,null,null);
int rv = cursor.getCount();
cusror.close();
return rv;
}
Note in all cases you should close the Cursor, as is shown in the last option, before returning, otherwise the Cursor's remain open and you have the potential of an exception due to too many being open.
The above is in-principle code and has not been checked or run and therefore may have some errors.

Select some data from SQLite using a date filter?

I want to select some data from a database table using a filter by date (date column is: [searchDate] DATETIME DEFAULT CURRENT_TIMESTAMP,)
In this pic, I'm using SQLite Expert and a filter by date:
and this code is for getting the current year and month:
DateFormat YEAR_FORMAT = new SimpleDateFormat("yyyy");
DateFormat MONTH_FORMAT = new SimpleDateFormat("MM");
YEAR_DATE = YEAR_FORMAT.format(new Date());
MONTH_DATE = MONTH_FORMAT.format(new Date());
Date date = new Date();
Log.d("Month", YEAR_FORMAT.format(date) + " " + MONTH_FORMAT.format(date));
and the cursor query in my app for getting a list filtered by date (current year):
public List<Moment> MOMENT_YEAR(String year) {
try {
Moment MOMENT_TABLE;
List<Moment> MOMENTS = new ArrayList<>();
DB_HELPER.openDatabase();
db.beginTransaction();
Cursor MOMENT_CURSOR = db.rawQuery("SELECT * FROM tblMoment WHERE strftime('%Y', searchDate) =" + year, null);
db.setTransactionSuccessful();
MOMENT_CURSOR.moveToFirst();
while (!MOMENT_CURSOR.isAfterLast()) {
MOMENT_TABLE = new Moment(MOMENT_CURSOR.getInt(0), MOMENT_CURSOR.getString(1), MOMENT_CURSOR.getString(2), MOMENT_CURSOR.getString(3),
MOMENT_CURSOR.getString(4), MOMENT_CURSOR.getString(5), MOMENT_CURSOR.getInt(6), MOMENT_CURSOR.getInt(7) != 0);
MOMENTS.add(MOMENT_TABLE);
MOMENT_CURSOR.moveToNext();
}
MOMENT_CURSOR.close();
return MOMENTS;
} catch (Exception e) {
return null;
} finally {
db.endTransaction();
DB_HELPER.closeDatabase();
}
}
I tried, but nothing happens and the list is null (empty).
I have most dates in the current year.
Isn't it clear? Surround the year variable with the SQL string delimiters (') in your query.
Cursor MOMENT_CURSOR =
db.rawQuery("SELECT * FROM tblMoment WHERE strftime('%Y', searchDate) = '" + year + "'", null);
Or simply use a parametric query (the string delimiters will be handled for you by Android).
Cursor MOMENT_CURSOR =
db.rawQuery("SELECT * FROM tblMoment WHERE strftime('%Y', searchDate) = ?", new String[]{year});
SELECT * FROM transactionList WHERE transactionDate BETWEEN '2018-04-29' AND '2018-05-29' LIMIT 20;
try this query and it will work like wow :)
Please check the question
Filter Not Working on date

How to Fetch data from database by passing two numbers as parameters?

i want to get some data from my database by passing 2 values like
getdata("1","5");
My function in database and the id is stored as String in database.
getdata(String FromMember_id,String ToMember_id){
}
I have also cast the id to get data but I didnt get data
Query is
"SELECT * FROM MilkCollection WHERE cast(member_code as REAL)
BETWEEN '"+ FromMember_id + "' AND '" +ToMember_id+ "' ";
When is use this Query without casting
"SELECT * FROM MilkCollection WHERE member_code '"+ FromMember_id + "'
AND '" + ToMember_id + "'"
and when i dont cast the member_code and do the same query it shows data but it shows the other data other id like 17,18,19 i guess its taking the starting value of 17,18,19 because there is 1 in starting of them.
As i understand your issue, you need to type cast your passing values to REAL which sure gives you a workaround solutions.
"SELECT * FROM MilkCollection WHERE cast(member_code as REAL) >='"+ FromMember_id + "' AND cast(member_code as REAL) <= '" + ToMember_id + "' ";
Description: Just because you are passing string values using your member function which causes uncertainty while fetching data from your database.
Here is some working code for sending objects for a get. You can compare and see where you have taken a misstep.
public String getPreachLogString(long day, String time) {
String selectQuery;
SQLiteDatabase db;
Cursor cursor;
String myPath = DATABASE_PATH + DATABASE_NAME;
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
selectQuery = "SELECT * FROM TABLE WHERE day = " + day + " AND time = \"" + time + "\"";
cursor = db.rawQuery(selectQuery, null);
To use strings in search I wrap string in \" where you wrap in '. Not sure why you are storing member IDs as string, assuming you have letters involved, but try casting member_code as TEXT to make a logical comparison between the 2 objects.
What you are trying to accomplish is possible I do it all the time. You just need to compare properly.
public ArrayList<String> getMonthlyWork(int year, int month) {
long thismonth = 0;
long nextmonth = 0;
String selectQuery;
SQLiteDatabase db;
ArrayList<String> result = new ArrayList<>();
SimpleDateFormat formatDate = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
String myPath = DATABASE_PATH + DATABASE_NAME;
Calendar c = Calendar.getInstance();
c.set(year, month, 1);
thismonth = c.getTimeInMillis();
if (month < 11) {
c.set(Calendar.MONTH, month + 1);
} else {
c.set(Calendar.MONTH, 0);
c.set(Calendar.YEAR, year + 1);
}
nextmonth = c.getTimeInMillis();
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
selectQuery = "SELECT * FROM TABLE WHERE day >= " + thismonth + " AND day < " + nextmonth;
Seems like John Bravdo already given you a working example
Let me address following 2 areas:
1. Why following SQL is not returning result?
Code:
"SELECT * FROM MilkCollection WHERE cast(member_code as REAL)
BETWEEN '"+ FromMember_id + "' AND '" +ToMember_id+ "' ";
With parameter value:
SELECT * FROM MilkCollection WHERE cast(member_code as REAL)
BETWEEN 1 AND 5;
Answer: Your table does not has any record containing value 1 to 5, but it does has record with value 17, 18, 19. Try pass the value 17 and 19 instead of 1 and 5, then it should return value. Moreover, test the SQL in database directly to confirm it does return data before checking in your program
Poor performance
Using a function call on any indexed column, e.g. cast(member_code as REAL), will not able to make use of index (regular index). Therefore, this SQL going to scan the entire table. You will start to see poor performance as the table size grow. Therefore, you need to use a column that is integer type in order to filter by integer value. You can add this column later after you have bandwidth. If the table is just a 1MB in disk, then you need to consider how many concurrent users are going to trigger this SQL call. If there are 1000 users running it concurrently, then it will cause 1GB of disk I/O (although DB engine could cache it) and it will be slow as well

Get data between current date to last month date from SQLite database

I need to get data in between current date to last month (means last 30 days) from SQlite.
Here is code to get list of all data but i get nothing from this.
public List<Birthday> getWeekBirthdays() {
List<Birthday> birthdays = new ArrayList<Birthday>();
SQLiteDatabase db = this.getReadableDatabase();
Calendar theEnd = Calendar.getInstance();
Calendar theStart = (Calendar) theEnd.clone();
theStart.add(Calendar.DAY_OF_MONTH, -30);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String start = dateFormat.format(theStart.getTime());
String end = dateFormat.format(theEnd.getTime());
String dateQuery = "SELECT * FROM " + TABLE_Birthday + " WHERE "
+ KEY_Event_Date + " BETWEEN " + start + " AND " + end;
Log.e(LOG, dateQuery);
Cursor c = db.rawQuery(dateQuery, null);
Log.e(LOG, "no of birthday : " + c.getCount());
if (c.moveToFirst()) {
do {
Birthday birthday = new Birthday();
birthday.setName(c.getString(c.getColumnIndex(KEY_User_Name)));
birthday.setEventType(c.getString(c
.getColumnIndex(KEY_Event_Type)));
birthday.setEventDate(c.getString(c
.getColumnIndex(KEY_Event_Date)));
birthday.setId(c.getInt(c.getColumnIndex(KEY_ID)));
birthdays.add(birthday);
} while (c.moveToNext());
}
return birthdays;
}
I do not get error please help me and tell me how to get these data.
Thanks
One way is
String query="SELECT * from "+TABLE_Birthday +" WHERE "+ KEY_Event_Date +" >= date('now','localtime', '-30 day')";
Cursor c = myDataBase.rawQuery(query,null);
It will fetch last 30 days records from today. but your KEY_Event_Date must have values in yyyy-MM-dd then only it works.
You can use this condition in your SQL query
date('now','-29 day')
This query gives you a date range of 30 days

How to get the values between current date and current date of previous year in sqlite in Android

I tried to get the data from sqlite database between current date one year before. I used the following code. But it didn't provide the data. Consider the current date is 25-10-2013. There is data for 25-09-2013. But the code inside do, doesn't execute. I don't get what is wrong in the code. The same way, I used for 3 months before and 6 months before, they work fine.
DateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal11 =Calendar.getInstance();
cal11.add(Calendar.MONTH, -12);
String one_year_before = cur_format1111.format(cal11.getTime());
Log.v("one_year_before", one_year_before);
Query to select data:
Cursor cur21 = db.rawQuery("SELECT * FROM " + TIMER_TABLE
+ " WHERE cur_date BETWEEN ? AND ?", new String[] {
one_year_before, cur_form_Date });
if (cur21 != null) {
if (cur21.moveToFirst()) {
do {
has_valuesyear = true;
String reader_name_db_service = cur21.getString(cur21
.getColumnIndex("username"));
Log.v("reader_name_db_service21",
reader_name_db_service);
if (reader_name_db
.equalsIgnoreCase(reader_name_db_service)) {
String tot_reading_time = cur21.getString(cur21
.getColumnIndex("tot_reading"));
Log.v("tot_reading_time21", tot_reading_time);
String cur_date = cur21.getString(cur21
.getColumnIndex("cur_date"));
Log.v("cur_date21", cur_date);
one_year_set.add(reader_name_db_service + "~"
+ cur_date + "~" + tot_reading_time);
}
} while (cur21.moveToNext());
}
}
cur21.close();
db.close();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
You would first have to store your dates as character in ISO format. Then your query will work.
Maybe give this a shot
Cursor cursor = db.query(TABLE_NAME, String[] {"column1", "column2"}, "cur_date BETWEEN " + year_before + " AND " + year_after +";",null,null,null,null,null);
The string array of columns, in your case, will contain all of your columns. The last null's are for ordering and limits.

Categories

Resources