Get all dates by month in android database - android

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'

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.

Android - SQLite Comparing system date to date in database

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.

SQLiteDatabase Query in android

Am having a table card with colums id,name, content,status, date.
i want to take id,name,content condition is status <= cards.STATUS also have to sort it by date
How i have to do this.
am doing like,
private Cursor c;
String[] cols = { id,name, content };
c = cardsDB.query(CARDS_TABLE_NAME, cols, "status <=" + Card.STATUS, null, null, null, "date desc");
if (c.moveToFirst()) {
do {
CardArray.add(new Card(c.getInt(0), c.getInt(1), c.getString(2)));
} while (c.moveToNext());
}
c.close();
When you have the complicated query , its better to use raw query not query method.
This is an example of how to implement a raw query:
String query= "Select id,name ,content from CARDS_TABLE_NAME Where status <= ? date desc";
Cursor c= database.rawQuery(query, new String[]{Card.STATUS});

How to select data between two date range in android SQLite

I have table which contains data along with created on date. I want to select data from table according to two given date ranges, or of one particular month.
I am not sure how to do that, as created on column is of type text and is stored as dd-MM-yyyy HH:mm:ss
I am using rawQuery() to fetch data.
You can do something like this:
mDb.query(MY_TABLE, null, DATE_COL + " BETWEEN ? AND ?", new String[] {
minDate + " 00:00:00", maxDate + " 23:59:59" }, null, null, null, null);
minDate and maxDate, which are date strings, make up your range. This query will get all rows from MY_TABLE which fall between this range.
Here is some usefull
//Get Trips Between dates
public List<ModelGps> gelAllTripsBetweenGivenDates(String dateOne, String dateTwo) {
List<ModelGps> gpses = new ArrayList<>();
SQLiteDatabase database = dbHelper.getReadableDatabase();
final String columNames[] = {DBHelper.COLUMN_ID, DBHelper.COLUMN_NAME, DBHelper.COLUMN_LATITUTE, DBHelper.COLUMN_LONGITUDE, DBHelper.COLUMN_ALTITUDE, DBHelper.COLUMN_DATE, DBHelper.COLUMN_TYPE, DBHelper.COLUMN_TRAVEL, DBHelper.COLUMN_SPEED};
String whereClause = DBHelper.COLUMN_TYPE + " = ? AND " + DBHelper.COLUMN_DATE + " BETWEEN " + dateOne + " AND " + dateTwo;
String[] whereArgs = {"Trip"};
Cursor cursor = database.query(DBHelper.TABLE_NAME_GPS, columNames, whereClause, whereArgs, null, null, DBHelper.COLUMN_NAME + " ASC");
while (cursor.moveToNext()) {
ModelGps gps = new ModelGps();
gps.setId(cursor.getLong(cursor.getColumnIndex(DBHelper.COLUMN_ID)));
gps.setName(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_NAME)));
gps.setLatitude(cursor.getDouble(cursor.getColumnIndex(DBHelper.COLUMN_LATITUTE)));
gps.setLongitude(cursor.getDouble(cursor.getColumnIndex(DBHelper.COLUMN_LONGITUDE)));
gps.setAltitude(cursor.getDouble(cursor.getColumnIndex(DBHelper.COLUMN_ALTITUDE)));
gps.setDate(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_DATE)));
gps.setType(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_TYPE)));
gps.setTravel(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_TRAVEL)));
gps.setSpeed(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_SPEED)));
gpses.add(gps);
}
database.close();
cursor.close();
return gpses;
}

What is the sql query in SQLite, to retrieve the records from the database table for the last week, for the last month, and for the last year

I created a data base table using SQLite in my project, I want to retrieve records from the database for the last week, for the last month, for the last year, when user click on the specified Buttons. But I don't know how to retrieve the records. Is there any function exist to get these records accordingly ?
You'll need to construct a "where" clause like so:
ContentResolver cr = getContentResolver();
Cursor groupCur = cr.query(
Groups.CONTENT_URI, // what table/content
new String [] {Groups._ID, Groups.NAME}, // what columns
"Groups.NAME NOT LIKE + 'System Group:%'", // where clause(s)
null, // ???
Groups.NAME + " ASC" // sort order
);
I spaced this out so it's easier to explain, but this is what you typically see as:
Cursor groupCur = cr.query(Groups.CONTENT_URI, null, null, null, null);
I found the query
SELECT * FROM DATABASE_TABLE
WHERE strftime('%Y-%m-%d',DATE) >= date('now','-6 days') AND
strftime('%Y-%m-%d',DATE)<=date('now') order by DATE

Categories

Resources