I want to fetch records from sqlite database table called messages.
I have a column named like Message_dated in the form of following "Jan 20, 2015 10:31:23". But in the cursor it is giving as it is.But now i want only date from message_dated column i dont want time.I am using to call query like following.But it is giving full date and time.
ColumnName = DatabaseHelper.TABLE_MSGS.COL_MESSAGE_DATED,
ColumnId = DatabaseHelper.TABLE_MSGS.COL_MESSAGE_DATED
String[] columns = new String[] {
DatabaseHelper.TABLE_MSGS.COL_MESSAGE_ID + " as _id",
columnName, columnID };
cursor = db.query(DatabaseHelper.TABLE_MESSAGES_NAME,
columns, null, null, columnID, null, null);
Please tell me how can i do it.Thanks in advance.
you can't retrieve it without time because a date object is already found to return that, however you can manipulate it so you can store it in a string and use it in a different format using the code bellow:
String input = "Jan 20, 2015 10:31:23";
DateFormat inputFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
Date date = inputFormatter.parse(input);
DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy");
String output = outputFormatter.format(date);
hope this will help you.
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.
Am new for android development here is my doubt i have saved the datetime field as text in sqlite how to get the maximum datetime among these records how can i achieve this i came to know that it can be achieved through Max() query i tried but am not getting the result here let me post what i have tried so far:
Here is the Sqlite Query:
public String DateTime(){
String str="";
Cursor cursor = db.query(CustomerModel.CustomerTable , new String [] {"MAX(" + CustomerModel.Customer_LastMofiedFlag +")"}, null, null, null, null, null);
if(cursor.moveToFirst()) { // to move the cursor to first record
int index = cursor.getColumnIndex(CustomerModel.Customer_LastMofiedFlag);
str = cursor.getString(index);
} mcontext.getContentResolver().notifyChange(DB_Timetracker, null);
return str;
}
Is it possible to get the maximum datetime in text format am saving the datetime format in yyyy-MM-dd HH:mm:ss how can i achieve this!!
Maybe you can try to save it in long format?
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 am accessing Android MMS database to get the date of MMS message:
Uri mmsUri = Uri.parse("content://mms/");
ContentResolver contentResolver = getContentResolver();
String[] projection = {"_id", "date"};
Cursor cursor = contentResolver.query(mmsUri, projection, null, null, null);
long dateVal = cursor.getLong(cursor.getColumnIndex("date"));
//This date is always 1970
Date mmsDate = new Date(dateVal);
But the date I get is always 1970. Then, I found an answer for this. I need to set the projection to null (to return all columns) and then use the following code to get date value:
//A mystery column of index 2
long timestamp = cursor.getLong(2) * 1000;
//It works !
Date mmsDate = new Date(timestamp);
Everything until here is fine. But, now instead of geting all rows from MMS database, I need to select those rows which were sent after a certain date, which means I need to use selection & selection argument. Something like:
String selection = NAME_OF_MYSTERY_COLUMN_IDX_2 > minDate
Cursor cursor = contentResolver.query(mmsUri, projection, selection, null, null);
But I have no idea what is the name of the column with index 2, how could I achieve what I need ? Is there a workaround?
Your first code block is correct, except for the Date instantiation. That constructor expects the time in milliseconds, but the MMS table keeps dates in seconds. To correct this, simply multiply the value returned from the query by 1000.
Date mmsDate = new Date(dateVal * 1000);
For future reference, the Cursor#getColumnName() method will give you the String name for a given column index.
You can try this.
String selection = "date_sent" > minDate
https://developer.android.com/reference/android/provider/Telephony.BaseMmsColumns.html#DATE_SENT
I have a Sqlite database that works fine, I can insert rows with no problem, but when I try to do an update only one column get updated. I get a return value of 1, but only the column SCANNED get updated, that is the only column that already had a value of 0 and was change to 1.
public int UpdateScanInvoice(String Invoice, int scanned, String empname,
int empnum) {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd",Locale.US);
String formattedDate = df.format(c.getTime());
SimpleDateFormat tf = new SimpleDateFormat("hh:mm:ss",Locale.US);
String formattedTime = tf.format(c.getTime());
String strFilter = MySQLiteHelper.TICKETNR + "='" + Invoice +"'";
ContentValues scanvalues = new ContentValues();
scanvalues.put(MySQLiteHelper.LOADEMPNAME, empname);
scanvalues.put(MySQLiteHelper.SCANNED, scanned);
scanvalues.put(MySQLiteHelper.LOADEMPNUM, empnum);
scanvalues.put(MySQLiteHelper.LOADDATE,formattedDate);
scanvalues.put(MySQLiteHelper.LOADTIME, formattedTime);
SQLiteDatabase db = dbHelper.getWritableDatabase();
int rowUpdated = db.update(MySQLiteHelper.TABLE_INVOICE, scanvalues,strFilter, null);
return rowUpdated;
}
Maybe my original insert is wrong?
This is the original insert.
values.put(MySQLiteHelper.SCANNED, 0);
values.put(MySQLiteHelper.LOADDATE, "");
values.put(MySQLiteHelper.LOADTIME, "");
values.put(MySQLiteHelper.LOADEMPNAME, "");
values.put(MySQLiteHelper.LOADEMPNUM, "");
I the file has 19 columns and only the last 4 will not update or take any value when I do an insert.
I deleted the data recreated the database, same result.
Thanks,
KimHJ
Why are you again updating all the values You want to change the SCANNED value for that just update that value only like this..
scanvalues.put(MySQLiteHelper.SCANNED, scanned);
SQLiteDatabase db = dbHelper.getWritableDatabase();
int rowUpdated = db.update(MySQLiteHelper.TABLE_INVOICE, scanvalues,strFilter, null);
for updating only SCANNED this is enough but you are updating all the values..this will replace your all old data