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.
Related
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
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
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.
I'm trying to learn how to use database in Android and so far I have learned how to fetch all rows of data in the table, but I'm not sure how I'm going to use a SQL query to search for a value that is equal to the string value I pass to the method below?
I wonder if someone could add some simple code how to query the database with SQL in my code? Preciate the help! Thanks!
Something like this: String query = "Select * from DB_TABLE where TABLE_IMAGE_PATH = filePath";
// Read from database
public String readContacts(String filePath){
String[] columns = new String[]{TABLE_ID, TABLE_IMAGE_PATH, TABLE_CONTACT_NAME, TABLE_CONTACT_NUMBER, TABLE_CONTACT_ADDRESS};
Cursor c = db.query(DB_TABLE, columns, null, null, null, null, null);
int id = c.getColumnIndex(TABLE_ID);
int imagePath = c.getColumnIndex(TABLE_IMAGE_PATH);
int name = c.getColumnIndex(TABLE_CONTACT_NAME);
int number = c.getColumnIndex(TABLE_CONTACT_NUMBER);
int address = c.getColumnIndex(TABLE_CONTACT_ADDRESS);
String result = "";
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(id) + " " + c.getString(imagePath) + " " + c.getString(name) + " " + c.getString(number) + " " + c.getString(address);
}
return result;
}
You can search Query
its for exact string
String query = "Select * from DB_TABLE where TABLE_IMAGE_PATH like '"+filePath+"';
if value contains your string
String query = "Select * from DB_TABLE where TABLE_IMAGE_PATH like '%"+filePath+"%';
if value needs from last
String query = "Select * from DB_TABLE where TABLE_IMAGE_PATH like '%"+filePath+"';
if value needs from first
String query = "Select * from DB_TABLE where TABLE_IMAGE_PATH like '"+filePath+"%';
put these
SQLiteDatabase dbR = this.getReadableDatabase();
Cursor cur = dbR.rawQuery("query", null);
return cur
using this cursor you can get value.
you can do that easily by modifying your query code to:
String[] columns = new String[]{TABLE_ID, TABLE_IMAGE_PATH, TABLE_CONTACT_NAME, TABLE_CONTACT_NUMBER, TABLE_CONTACT_ADDRESS};
Cursor cursor = db.query(ANSWERS_TABLE,
columns,
columns[1] + " = ?", new String[]{filePath}, null, null, null);
Take a look here : SQLiteDataBase Query
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 .