The basic idea of what I want to achieve is to make a comparison between the current Android system date and an existing date in a SQlite database.
The idea is to 1.) If the database does not contain contain a entry with today's date, then allow new entry
2.) If the database already contains an entry from today's date, then revoke entry and output error message.
My DBAdapter currently has a method that does the following:
public Cursor getDate(String date) {
String where = KEY_DATE + "=" + date;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c !=null) {
c.moveToFirst();
}
return c;
}
and the method i'm using to make the comparison is:
public void addRecord (View view){
db.open();
Cursor cursor = db.getDate(dateString);
if (cursor.moveToFirst()){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Date");
builder.setMessage("Entry for today exists, would you like to update this instead?"); builder.setPositiveButton("OK", null);
#SuppressWarnings("unused")
AlertDialog dialog = builder.show();
db.close();
}
else{
Do other work..
both Date's used for comparison is formatted using this code:
long longDate = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateString = sdf.format(longDate);
where I'm simply calling 'dateString'
My trouble is that it doesn't perform the correct checks and skips my else statement completely even tho i know there is an existing 'date' in the database. Is my SQL statement correct?
Try setting up the query like this:
db.query(true, DATABASE_TABLE, ALL_KEYS, KEY_DATE + "=?", new String[] {date}, null, null, null, null);
I use dates on my database, But I save them as a long value with the getDate() function.
Also I have found problems depending on the type of Date variable you use.
I like java.util.Date and never ever use the sql date variable.
I do where conditions for my data and all comparison are by getTime() which is a Long value.
With the long value you get from the database just do new Date( longValue ) and that way you get the correct date variable.
Related
All!
My code:
This method needs to check current date and if it is changed it will make new record in db.
public static void updateHintBase(SQLiteOpenHelper database)
{
String currentDate = getDateInString();
SQLiteDatabase db = database.getReadableDatabase();
Cursor cursor = db.query("HINTS",
new String[]{"CURRENT_DATE"},
"CURRENT_DATE = ?",
new String[]{currentDate},
null, null, null);
int countRow = cursor.getCount();
cursor.close();
if (countRow==0)
{
ContentValues values = new ContentValues();
values.put("CURRENT_DATE", currentDate);
values.put("SPENT", 0);
values.put("TOTAL", TOTAL_HINTS);
db.insert("HINTS", null, values);
}
db.close();
}
This method transforms date to String :
private static String getDateInString()
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(new Date());
return date;
}
Table structure:
db.execSQL("CREATE TABLE HINTS (CURRENT_DATE TEXT PRIMARY KEY , "
+ "SPENT INTEGER,"
+ "TOTAL INTEGER);");
But my code doesn't work. First time it works, but the second time when date was changed my first method finds element in cursor anyway...
For example:
1) Today 16.01.2017. My application was executed. Everything is all right.
2) Today 18.01.2017. My application was executed and I expect that method cursor.getCount() will return to me 0 and new row with new date will be created. But it returns to me 1. etc.
You may have to set cursor to cursor.MoveToNext() You are also closing the cursor before you get the information which may be the problem. Lastly looping through the cursor is the most efficient way to get more that one piece of information.
Please try this query:
cursor = db.rawQuery("select count(YOUR_ID) from HINTS where CURRENT_DATE = ? ", new String[] {currentDate});
Oh! I found my mistake!
Word "CURRENT_DATE" is reserved by SQL.
https://docs.oracle.com/cd/B28359_01/server.111/b28286/functions037.htm#SQLRF00628
That's why my code works incorrect.
I change "CURRENT_DATE" to "TODAY" an now it works fine.
I'm struggling with the implementation of dates in SQLite3 (for android). According to the documentation (https://www.sqlite.org/datatype3.html and http://www.sqlite.org/lang_datefunc.html), SQLite doesn't have datatypes for date and time specifically and therefore it can be either stored as a TEXT or as an INTEGER. I've tried both, but they give the same erroneous results. After reading a lot on the internet and trying everything I can think of, I come here as a last resort.
So, now for the problem. The idea is actually very simple. I have a table containing items, with a date column. Now I want to select all items from this database that have a date of today, or before (i.e. today or in the past). In my current implementation I store dates as integers, since most people seem to agree that that is the way to go.
Below is the (simplified) code for inserting an item.
Calendar calendar = GregorianCalendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0); // Might not be necessary
calendar.add(Calendar.DAY_OF_YEAR, 4); // Today plus 4 days
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_DATE, calendar.getTimeInMillis()); // Today as integer/long
long id = db.insert(TABLE_ITEMS, null, values); // Add to db
And next I want to select the items where the date is equal to or lower than today:
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
String[] columns = new String[]{COLUMN_ID, COLUMN_TEXT, COLUMN_DATE};
String[] selectArg = new String[]{"date('now')"};
Cursor cItems = db.query(TABLE_ITEMS, columns, COLUMN_DATE + "<= ?", selectArg, null, null, null);
//Cursor cItems = db.query(TABLE_ITEMS, columns, "strftime('%Y-%m-%d'," + COLUMN_DATE + ")" + select, selectArg, null, null, null);
//Cursor cItems = db.query(TABLE_ITEMS, columns, "date(" + COLUMN_DATE + ")" + select, selectArg, null, null, null);
Now all rows are selected, also the rows with a date in the future. Could anyone tell me what I need to do differently?
Thanks in advance!
Edit
I found out that sqlite stores date integers in seconds (is that correct?). So that would mean that value I put in the database should be Math.round(calendar.getTimeInMillis()/1000, to get it in seconds right? But then it makes even less sence, since a date in milliseconds should always be larger than a date in seconds. Anyhow, I tried that, but it doesn't work either.
Thanks to the insights CL. gave me, I fixed some trivial errors I made.
Looking back at the SQLite documentation, I figured that there are two ways of storing a date without a time. A Julian day number or a date string YYYY-MM-DD. There is no readily available function to get a Julian day number in java/android, so therefore I chose to go back to the string format again.
A second, mistake I figured out just now is that the selectArgs are considered text and therefore, putting the date('now', 'localtime') in there won't work.
Below are the final scripts that do work.
Calendar calendar = GregorianCalendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0); // Might not be necessary
calendar.add(Calendar.DAY_OF_YEAR, 4); // Today plus 4 days
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
ContentValues values = new ContentValues();
values.put(COLUMN_DATE, dateFormat.format(calendar.getTime())); // Date as string
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
long id = db.insert(TABLE_ITEMS, null, values); // Add to db
And to get the data back:
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
String[] columns = new String[]{COLUMN_ID, COLUMN_TEXT, COLUMN_DATE};
String[] selectArg = new String[]{};
Cursor cItems = db.query(TABLE_ITEMS, columns, COLUMN_DATE + "<= date('now', 'localtime')", selectArg, null, null, null);
CL., many thanks for your help! In the end it was so simple...
Neither date() nor strftime('%Y-%m-%d') returns a date in your format.
To convert a date into the seconds format, you would have to use strftime('%s', ...), and convert the resulting string into a number.
I have table in database where one of column is for date in Long. Is there any simple way to get all dates by month? For example I need all dates for October. For day I use:
public static List<Plan> getPlanListByMonth(SQLiteDatabase db, DateTime date) {
String where = "date" + " = '"+ "2015-11-04" +"'";
Cursor cursor = db.query(TABLE_NAME, null, where,
null, null, null, null, null);
return getPlanList(cursor);
}
but I have no idea how to create where condition to get all values by month.
You can use strftime() function
SELECT * FROM TABLE_NAME WHERE strftime('%m', 'date') = '11'
Hy Guys, I am Beginner Android Developer. I need your help. i want to insert data into 2 tables of sqlite tblorder, and orderdtl. on orderdtl i have to insert data from multiple item from listview. i try to toast all variable that i want to inserted. their all appears. but when i try to save it. i get those error.
this is my DBDataSource.java
public order createorder(String orderid, String notes, long outletid) {
ContentValues values = new ContentValues();
values.put(DBHelper.ORDER_ID, orderid); // inserting a string
values.put(DBHelper.NOTES, notes); // inserting an int
values.put(DBHelper.OUTLET_ID, outletid); // inserting an int
long insertId = database.insert(DBHelper.TABLE_ORDER, null,
values);
Cursor cursor = database.query(DBHelper.TABLE_ORDER,
allorder, DBHelper.ORDER_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
order neworder = cursorToorder(cursor);
cursor.close();
return neworder;}
private order cursorToorder(Cursor cursor) {
order order = new order();
order.setorderid(cursor.getString(cursor.getColumnIndex(DBHelper.ORDER_ID)));
order.setorderdate(cursor.getString(cursor.getColumnIndex(DBHelper.ORDER_DATE)));
order.setnotes(cursor.getString(cursor.getColumnIndex(DBHelper.NOTES)));
order.setoutletid(cursor.getLong(cursor.getColumnIndex(DBHelper.OUTLET_ID)));
return order;
}
The error refer to this code
Cursor cursor = database.query(DBHelper.TABLE_ORDER,
allorder, DBHelper.ORDER_ID + " = " + insertId, null,
null, null, null);
And this code
order.setorderid(cursor.getString(cursor.getColumnIndex(DBHelper.ORDER_ID)));
orderid is string, i try to get from yyyyMMddHHmmss.this is the code:
private String orderid(){
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyyMMddHHmmss", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
I would be very grateful for any help that you give.Thank You.
The query didn't match any rows. Check the result of moveToFirst() to see whether the operation succeeded and only then access cursor data.
Example:
order neworder = null;
if (cursor.moveToFirst()) {
order neworder = cursorToorder(cursor);
}
cursor.close();
return neworder;
The insertId you get from insert() is the sqlite row id for the row. It's likely not the same as ORDER_ID. To make a column an alias for rowid, declare it as INTEGER PRIMARY KEY.
The error I see in logcat is not about _Player_8, but about the unknown column "KEY_Team_Name"
The problem is in your activity, the line prior to the last one:
String EntryA =String.valueOf( db.getentry("Ravirrrr", "KEY_Team_Name"));
It should be:
String EntryA =String.valueOf( db.getentry("Ravirrrr", DatabaseHandler.KEY_Team_Name));
And the DatabaseHandler should have all column names public, as the getentry method requires a column name.
Edit: adding an answer to the question in the comments below.
After calling db.query, you should check if you got something by calling Cursor.isAfterLast(). If true, the select returned an empty result set.
In your example, you WILL get an empty result set as the code creates an entry with "Ravi" as the team name, then asks for a team named "Ravirrrr".
I have a database which has a column of dates in milliseconds. I'm trying to perform a query which allows me to retrieve only the dates that are greater than the current system time and in ascending order.
I've tried this query, but it causes my app to force close. I'm not sure whether the problem is the where clause part or the orderby clause part or both.
Here is what I done, your help would be most appreciative.
long lowestDate = 0;
long currentTime = System.currentTimeMillis();
String CT = Long.toString(currentTime);
String[]c = {CT};
mDb = mDbHelper.getReadableDatabase();
String[] dates = {KEY_DT};
Cursor getDate = mDb.query(DATABASE_TABLE, dates, dates + "> ?", c, null, null, dates + "ASC");
getDate.moveToFirst();
while(getDate.isAfterLast() == false)
{
lowestDate = getDate.getLong(0);
getDate.moveToNext();
}
It seems you are using query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
selection argument description:
A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table.
You should correct that. I think that's an issue, because you are calling toString() method on dates variable, which is an Array.