Query a database with a string that contains "/" - android

I store a date in my database format "MM/dd/yyyy" and I want to do a query by a specific date but when I make the query the cursor returns nothing.
Is it because of the "/" that is in the string or something else? And yes I know the date is stored properly in the database
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
return new CursorLoader(getActivity(),Games.GAMES_URI,new String[] {Games.GAMES_ID},Games.GAMES_DATE + "="+dt,
null,null);
}
converting the date
public convertDate(Calendar date){
mDate = date;
Date d = new Date(date.getTimeInMillis());
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
dt = df.format(d);
}

The query you are trying to do will look like:
... WHERE games_date=08/11/2012
where it needs to be:
... WHERE games_date="08/11/2012"
(assuming that games_date is the name of the column -- replace as needed)
Try Games.GAMES_DATE + "=?" for your fourth CursorLoader constructor parameter, and {dt} for your fifth CursorLoader constructor parameter, and Android/SQLite will automatically add your quotation marks for you where needed, assuming that your ContentProvider is backed by SQLite.
Also, you might consider storing your date in some other format. If you want it to be a string, yyyy-MM-dd (or yyyy/MM/dd) is a better choice, as it will sort correctly in chronological order. If you do not need it to be a string, just storing getTimeInMillis() in an INTEGER column will make it easier to convert to and from Date objects without messing with string conversions.

Related

how to compare string date with the format "dd-MM-yyyy" to empty string

hello guys for the last three days I have been working on a simple query , but it is just not working , I'm trying to prevent register departure without having registered arrival , here is the code in my DB helper,not sure what is wrong with that query!!
public Boolean HasShowedUpToday(int check_id)
{
Boolean attend;
SQLiteDatabase db=this.getWritableDatabase();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault());
time=Calendar.getInstance().getTime();
String dateoftoday= dateFormat.format(time);
Cursor c = db.rawQuery("SELECT * FROM attendance where user_id = '"+check_id+"' and arrival_time ='"+dateoftoday+"' and departure_time ='';", null);
if (c.moveToFirst())
{
attend=true;
}
else
{
attend=false;
}
return attend;
}
First of all do not construct queries like that. This is very wrong habit which will made you in future to write code which is vulnerable to SQL injections.
Use rawQuery (String sql, String[] selectionArgs).
So it should look like this:
Cursor c = db.rawQuery("SELECT * FROM attendance where user_id = ? and arrival_time = ? and departure_time IS NULL",
new String[] { check_id, dateoftoday} );
Also take a look on this SO answer. And this answer looks even better - store dates as number of milliseconds since EPOCH time.

Android SQlite: Querying table rows by date range from today backwards?

I get a date from the server in "MM/dd/yyy" form, then I convert it into milliseconds using the following function:
public static long getSimpleDateToMillis(String simpleDate) throws ParseException {
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date date = formatter.parse(simpleDate);
return date.getTime();
}
Then afterwards I save the result into the database as int.
Right now I'm stucked in what seems like a dead-end for me. I can't find a way through searching and from my stock knowledge on how I would be able to filter my cursorloader by project_date column which is saved as integer in the database.
In what way would I be able to query such that it would:
Select all row from projects table where the project_date is today and backwards (yesterday and so on).
I tried this one but seems to be really not the answer.
String [] projection = new String []{};
String selection = "datetime("+ ProjectsEntry.COLUMN_PROJECT_DATE + "/1000, 'unixepoch') =? ";
String [] selectionArgs = new String[]{" date('now')"};
return new CursorLoader(this,
JobsContract.JobsEntry.CONTENT_URI,
projection,
selection,
selectionArgs,
null);
I haven't found any other reference that would point me, so I'm hoping someone might also have encountered this perhaps.
This is how I do something quite similar, but using full timesteamp i.e. long rather than int.
First I have this method to get the TimeStamp, to get today's date/time as of midnight (bar 1 millisecond):-
/**
*
* #return 1 millsecond before midnight today
*/
private long getDateTimeOfAllofToday() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH,1); // tomorrow
cal.set(Calendar.MILLISECOND,0);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MINUTE,0);
cal.set(Calendar.HOUR_OF_DAY,0);
cal.add(Calendar.MILLISECOND,-1);
return cal.getTimeInMillis();
}
Then I create the respective where clause e.g. :-
filter = DBRulesTableConstants.RULES_ACTON_COL +
" <= " +
Long.toString(getDateTimeOfAllofToday());
This is used via a rawQuery so not exactly what you want but easy enough to to change " <= " to " <=?" and then use
String [] selectionArgs = new String[]{Long.toString(getDateTimeOfAllofToday())}; or a modified version to get integer.

Trouble to extract dateTime with Sqlite Android

this is my code :
String sqlcomment="SELECT createdBy, text, documentPath, editedDate, actualityCommentID, actualityID FROM ActualityComment WHERE actualityID="+actual.getCode();
Cursor curcomment;
SQLiteDatabase dbase = openOrCreateDatabase("leymaxdb.sqlite",SQLiteDatabase.CREATE_IF_NECESSARY,null);
curcomment = dbase.rawQuery(sqlcomment, null);
int maxid=0;
if (curcomment.moveToFirst()) {
do
{
System.out.println(curcomment.getString(3).toString());
}while (curcomment.moveToNext());
}
dbase.close();
the error is in this line because i need to print editedDate from database and this is DateTime
System.out.println(curcomment.getString(3).toString());
And this is the android error :
java.lang.NullPointerException
check what the value of actual.getCode() is and also check for cursor that cursor is null or not. then access it . may be database does not contain any record for that query.
after getting date as string pass that value to SimpleDateFormat to make the date object.
First check, database created?
having value or not?
do it by taking .db file from file explorer.
once db having values,
then read date value from cursor and display like below:
Date date = new Date(curcomment.getString(3));
DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
mydate.setText("Time: " + dateFormat.format(date));

Order list of dates in String format

I've got a list which contains x records with dates. The thing is all my dates are in the String format and come as strings from the database.
I would really like to order my List by date (in String format) but I really have no clue how to do this.
Without further ado, this is my list, which is a custom list.
List<Finance> finances;
The list contains following fields:
public class Finance {
private int id;
private int categoryId;
private int limitId;
private double amount;
private String date;
private String description;
}
And this is the dateformat I have (in String):
16/10/2013
15/12/2013
15/11/2013
14/9/2013
How would I be able to sort this custom list by date? I've seen many examples with Collections.sort but I cannot use that because of my custom list type.
I've also seen some examples with Comparable but I didn't really understand those..
Could anybody tell me what would be the best way to achieve a chronical order by date of mist list please?
I would also like the most lightweighted method, to use as little resources as I can.
EDIT: I still didn't find a working solution (19/12) and still hope for a response here..
Thank you
Yenthe
Okay since there where no good answers and barely any responses I decided to dig into it until I fixed it.
The 'easiest' way to come around this is to insert all your dates into the database as yyyy-mm-dd format. For a great explenation on that part you should look here: https://stackoverflow.com/a/5733535/2262409
When you place the date in yyyy-mm-dd and just do a order by Date in your SQLite the dates will be ordered correct. When you place them in dd-mm-yyyy they will not be ordered correct.
Long answer short:
Solved it in the SQL part. I insert records in the format yyyy-mm-dd I get them by
String selectQuery = "SELECT * FROM Finance ORDER BY date desc";
And then I reformat them to dd-mm-yyyy right before the user sees it. Example:
String date = String.valueOf(values.get(position).getDate());
// we will format yyyy-mm-dd to dd-mm-yyyy for readability.
//the sql has ordered our dates correctly already.
String firstPartDate = date.substring(8, 10);
String secondPartDate = "/" + date.substring(5,7);
String thirdPartDate = "/" + date.substring(0,4);
String fullCorrectDate = firstPartDate + secondPartDate + thirdPartDate;
Log.i("firstpart", firstPartDate + secondPartDate + thirdPartDate);
dateFinance.setText(fullCorrectDate);

Sort DB data and display in list view

I get data from my DB using
cursor = db.query("WebLeadMaster", select, "condition1="+conditionVal1+
" and condition2="+ConditionVal2,null, null, null, "RegistrationTime DESC");
I am getting the data in my cursor alright. To display the data, i use the following code:
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,
R.layout.resultleadlookup, cursor, columns, to);
mAdapter.notifyDataSetChanged();
lstResult.setAdapter(mAdapter);
So, I cannot modify the contents of the cursor. The sort query has condition "RegistrationTime" which is a String data type. As you can see in the image below, it is not in a proper sorted format. (not according to date-time).
What changes should i make in my code so that it would sort properly according to date-time?
If i alter my DB query, to look like
cursor = db.query("WebLeadMaster", select, "condition1="+conditionVal1+
" and condition2="+ConditionVal2,null, null, null, null);
it gives an ascending order. All i want it the descending order.
The easiest suggestion would be to save the date in a different format (but still saved as string) into the database. If you would save the data into SQLite’s default date format (YYYY-MM-DD HH:NN:SS), you can easily sort the dates.
To display the date in your format, you would only just need to reformat the date into the correct format.
Well, i changed my table structure. I added another field "_id" to it. Set the property as AUTO INCREMENT to it, and sorted the list with respect to _id field.
If you r using ORM you can sort the data by timestamp.
ORM makes data insertion and data retrieval easier from database.
You have to include jar files to your project to use ORM...
since SQLite has no datetime type, store date type as LONG/INT/NUMERIC in SQLite (EPOCH time) it will be easier to sort
then add ViewBinder to Adapter
/*field in activity/fragment*/
final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //or other format that you wana to show in ListView
...
mAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Cursor cursor,
int columnIndex) {
final int id = view.getId();
switch (id) {
case R.id.id_of_textview_with_date_data:
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(cursor.getLong(columnIndex));
((TextView) view).setText(sdf.format(cal.getTime()));
return true;
}
return false;
}
});
... or as dennisg pointed store it as STRING/VARCHAR edit: in "yyyy-MM-dd HH:mm:ss" format

Categories

Resources