How to get a Maximum DateTime in sqlite android? - android

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?

Related

How to pass yyyy-mm String to yyyy-mm-dd datetime string to filter records from sqlite?

Here i have Datetime string in yyyy-mm-dd format like
2016-08-26
2016-09-21
2015-07-23
2016-04-25
What i need is if pass 2016-08 in parameter i need to get record of 2016-08-26 like that i need to get how can i achieve this so far what i have tried is
public List<CustomerModel>date(String year){
String countQuery ="SELECT * FROM "+CustomerModel.CustomerTable + " where " +CustomerModel.Customer_CreatedAt + " strftime('%Y-%m',"+CustomerModel.Customer_CreatedAt+") = "+year +"";
Cursor cursor = db.rawQuery(countQuery, null);
List<CustomerModel>list=new ArrayList<>();
if(cursor!=null && cursor.getCount()>0){
if(cursor.moveToFirst()){
do{
CustomerModel accountModel=new CustomerModel();
accountModel.setCreatedByName(cursor.getString(cursor.getColumnIndex(CustomerModel.Customer_CreatedBy)));
// accountModel.setCreatedat(cursor.getString(1));
list.add(accountModel);
}while (cursor.moveToNext());
}
}
if(cursor!=null){
cursor.setNotificationUri(mcontext.getContentResolver(),DB_Timetracker );
}
return list;
}
Am getting sqlite exception how to achieve this is it possible to do this Thanks in advance.
Try this query
select * from table_name WHERE created_date LIKE '2016-08%'
This will give you multiple records if you have more than one date for that particular year and month. Replace the date with your sting using string functions from the date field.

Need sqlite Query with substring

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.

Android MMS database, select rows by date from a mystery column

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

android cannt use data function in query

I cant get any result if i put "date('now', 'localtime')" in the query.
My original code is:
Cursor record = db.query(RECORD_TABLE, null, date(UTC_DATETIME,'localtime') = ? ",
new String[]{"date('now', 'localtime')"},null,null,null);
It doesn't return any result.
But I can get result if I use:
Cursor record = db.query(RECORD_TABLE,null, date(UTC_DATETIME,'localtime') = ? ",
new String[]{"2014-05-13"},null,null,null);
Is there a way that I can use "date('now', 'localtime')" in my query?
The whole point of parameters is to prevent their values from being interpreted as SQL expressions.
To call an SQL function, you have to put it into the SQL string:
Cursor record = db.query(RECORD_TABLE, null,
"date(UTC_DATETIME,'localtime') = date('now', 'localtime')",
null,null,null,null);
Please note that the localtime conversion affects both values in the same way, so you can omit it:
Cursor record = db.query(RECORD_TABLE, null,
"date(UTC_DATETIME) = date('now')",
null,null,null,null);
or even omit the first date call if the UTC_DATETIME column alread is in the correct yyyy-MM-dd format:
Cursor record = db.query(RECORD_TABLE, null,
"UTC_DATETIME = date('now')",
null,null,null,null);

Android SQlite date without a year?

In my Android app, I'm trying to retrieve a string from my database based on the date. But I don't want the year in the date (that way I only have to have 365 rows). The only way I've gotten it to work is in my DB, have the date in the Date column be in the format yyyyMMdd. If I change all the dates in the Date column to be in the format MMdd, the double digit months (like Oct, Nov, Dec) work, but the single digit months like Jan. or Sept. (01, 09) crash the app with the error CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0. I've tried the formats MM-dd, yyyy-MM-dd, in the DB and they crash the app with the error listed above. Is it not possible to have the date formatted with just MMdd in a Sqlite database? Any ideas?
MainActivity:
DBT = new SimpleDateFormat("MMdd", Locale.US);
tMMddStr = DBT.format(new Date(System.currentTimeMillis()));
private void getTH() {
dba.open();
tArray = dba.getTHA(tMMddStr);
dba.close();
optionB_TV.setText(todayArray[2]);
hideDayAtv.setText(todayArray[1]);
hideYearAtv.setText(todayArray[0]);
}
DBAdapter:
public String[] getTHA(String tMMddStr) {
String[] columns = new String[] { KEY_Y, KEY_MD, KEY_HA };
Cursor cursor = db.query(DB_TABLE, columns, KEY_DATE + "=" + tMMddStr,
null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
String hapT[] = new String[3];
hapT[0] = cursor.getString(0);
hapT[1] = cursor.getString(1);
hapT[2] = cursor.getString(2);
cursor.close();
this.db.close();
return hapT;
}
return null;
}
CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
This error means that you are trying to read an empty Cursor, simply check if the Cursor has any data before trying to read it:
if (cursor != null && cursor.moveToFirst()) {
As far as the single digit month problem, this could be related to the KEY_DATE column's data type. If KEY_DATE is any type of number, it will strip out the first 0. Try doing the same to tMMddStr.
(If this didn't help, post your tables CREATE statement and a few examples of how you are putting data into the database and pulling it out.)

Categories

Resources