why duration column in calendar Evens table does not get value set via provider?
ContentValues event = new ContentValues();
if(allDay==1) {
long days = (dtend - dtstart + DateUtils.DAY_IN_MILLIS - 1) / DateUtils.DAY_IN_MILLIS;
event.put("duration", "P" + days + "D");
} else {
event.put("duration", "P" + ((dtend-dtstart)/DateUtils.SECOND_IN_MILLIS) + "S");
}
Uri eventsUri =Uri.parse("content://com.android.calendar/events")
cr.insert(eventsUri, event);
Are you sure you are not dividing by zero?
The DateUtils.SECOND_IN_MILLIS might get zero as value and then it will not perform the calculation (it should crash I presume).
You might want to check it out. I'm no Android programmer, but that's the first thing I would check assuming the code has a valid syntax.
Related
I'm in the middle of developping a map app that enables user to send duration data that it takes him to get to another place, to the database (MySQL) , for this reason I tried to extract the double value of duration directely from url as it's showing in the method below :
#Override
public void setDouble(String result) {
String res[]=result.split(",");
Double min=Double.parseDouble(res[0])/60;
int dist=Integer.parseInt(res[1])/1000;
Duree.setText("Duration= " + (int) (min / 60) + " hr " + (int) (min % 60) + " mins");
Distance.setText("Distance= " + dist + " kilometers");
}
In this method it worked, but when I tried to do it like this :
url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins="+latt+","+lngg+"&destinations="+lt+","+lg+"&mode=driving&language=fr-FR&avoid=tolls&key=API_KEY";
String res[]=url.split(",");
Double duration=Double.parseDouble(res[0])/60;
It showed me that it's not a valid double value, knowing that I need to send this value when I click a button showed on a popup window after marker click (So the problem of inner class is posed).
Can you help me know what is the right way to do it ,if that is possible !
Don't expect your first result-field contains the duration but make your parsing a little more intelligent. Use, by example, the org.json library (introduction on json
Following code snippet should help a little:
LOGGER.debug("---google duration in seconds = {}", jsonElement.opt("duration") == null ? 0 : jsonElement.getJSONObject("duration").get("value"));
transportInfo.setDuration(jsonElement.opt("duration") == null ? 0 : (Integer) jsonElement.getJSONObject("duration").get("value"));
And, btw, I would recommend removing your API key ASAP from your post .... Be aware this key could be used by other people.
I have some moment in time in UTC timestamp. I create a DateTime object from it, and then try to enrich it with "(today)" or "(tomorrow)" explanation if it is so:
DateTime dateTimeUtc = new DateTime(this.timeUtc, DateTimeZone.UTC);
DateTimeFormatter dateTimeFormatter = DateTimeFormat.mediumDate();
String resultingString = dateTimeUtc.withZone(DateTimeZone.forTimeZone(TimeZone.getDefault()))
.toString(dateTimeFormatter);
if(dateTimeUtc.getDayOfYear() == DateTime.now(DateTimeZone.UTC).getDayOfYear()) {
resultingString += " (" + context.getResources().getString(R.string.today_caption) + ")";
} else if(dateTimeUtc.getDayOfYear() == DateTime.now(DateTimeZone.UTC).plusDays(1).getDayOfYear()) {
resultingString += " (" + context.getResources().getString(R.string.tomorrow_caption) + ")";
}
But - surprisingly - my app does a TimeZone conversion somewhere. Device is set for eastern europian time (GMT+3 currently) and it works like this: 2 june 2:59 AM is treated like today (0_o) 2 june 3:01 is already a tomorrow.
Can someone point to an error?
P. S.: if there's a better way to qualify DateTime as 'today' or 'tomorrow' - I would be great to see any ideas.
Since no answer provided, I'll post workaround of my own. Though still have no idea why comparison of two UTC-zoned timestamp'ed days of year gives user's timezone offset.
Here's the code that works correctly for me:
if(dateTimeUtc.withZone(userZone).getDayOfYear() == DateTime.now(DateTimeZone.UTC).withZone(userZone)
.getDayOfYear()) {
resultingString += " (" + context.getResources().getString(R.string.today_caption) + ")";
} else if(dateTimeUtc.withZone(userZone).getDayOfYear() == DateTime.now(DateTimeZone.UTC).withZone(userZone)
.plusDays(1).getDayOfYear()) {
resultingString += " (" + context.getResources().getString(R.string.tomorrow_caption) + ")";
}
this produces correct check if given day is in interval from now till start of tomorrow or from start of tomorrow till start of the day after.
I need that every time I make a change to a certain record from a table in SQLite, in the column lastChangedDate to set the time from France. Here is the structure of my table :
CREATE TABLE name(
id VARCHAR(36) PRIMARY KEY
, pos_report_id VARCHAR(36)
, path_name VARCHAR(64)
, photo_name VARCHAR(64)
, from_scratch INTEGER DEFAULT 0
, lastChangedDate DATETIME DEFAULT (DATETIME('now', 'utc', '1 hours'))
)
I see that DATETIME('now') returns 2 hours before my real time and DATETIME('now', 'utc', '1 hours') returns with 3 hours before my time. Why is happening this? I need the application to work in more countries, so I cannot use localtime.
Any idea how to solve this?
I have the same problem (using sqlite on Raspbarry Pi). 'utc' obviously only calcultes the difference according to location and timezone. I got it running like this:
select datetime(datetime('now', 'localtime'), 'utc');
Also check out the other variation of my VIEW [NOW] for sensor logging purpose.
CREATE VIEW [NOW] AS
SELECT datetime('now', 'localtime') as LOCAL,
datetime(datetime('now', 'localtime'),'utc') as UTC,
substr(datetime('now', 'localtime'),1,17)||'00' as TimeSlot_1min,
substr(datetime('now', 'localtime'),1,15)||'0:00' as TimeSlot_10min,
substr(datetime('now', 'localtime'),1,14)||'00:00' as TimeSlot_1h;
try datetime('now','localtime') instead of DATETIME('now', 'utc', '1 hours')
Ok dont use default time for lastChangedDate
CREATE TABLE name(
id VARCHAR(36) PRIMARY KEY
, pos_report_id VARCHAR(36)
, path_name VARCHAR(64)
, photo_name VARCHAR(64)
, from_scratch INTEGER DEFAULT 0
, lastChangedDate DATETIME)
)
then when you want to add record to table, you can calculate the time in France and add this value to your database
//Calendar cal = Calendar.getInstance();
//Log.v("hata",String.valueOf(cal.get(Calendar.HOUR)));
Calendar c = Calendar.getInstance();
// It is local time
Log.v("time",String.valueOf(c.getTime()));
TimeZone z = c.getTimeZone();
int offset = z.getRawOffset();
if(z.inDaylightTime(new Date())){
offset = offset + z.getDSTSavings();
}
// france is GMT2
int offsetHrs = offset / 1000 / 60 / 60;
int offsetMins = offset / 1000 / 60 % 60;
// Offsets
Log.v("time",String.valueOf(offsetHrs));
Log.v("time",String.valueOf(offsetMins));
c.add(Calendar.HOUR_OF_DAY, (-offsetHrs));
c.add(Calendar.MINUTE, (-offsetMins));
// FRANCE time
Log.v("time",String.valueOf(c.getTime()));
The code i'm working on lists the events from the calendar, i need to limit the range of dates, and in the examples i see this code:
// Construct the query with the desired date range.
Uri.Builder builder = Instances.CONTENT_URI.buildUpon();
ContentUris.appendId(builder, startMillis);
ContentUris.appendId(builder, endMillis);
I don't understand why appendId is used in this way. startMillis and endMillis are not ids, i would expect that the parameter name had to be provided eg "startdate" , It's not clear to me why this works, and what other parameters could be specified this way. Are there more parameters supported by appenedId? How can i know?
What appendId actually does is add a /# to your uri where # is a number. In your example (assuming startMillis = 1000 and endMillis = 3000 and the uri content://com.google.calendar/) this would mean your uri could end up like this:
content://com.google.calendar/1000/3000
This is something that a uri parser can pickup:
URIMatcher.addURI(AUTHORITY, calendar + "/#/#", DATE_RANGE);
Long story short: appendId is just a convenient and type-safe way to add an integer to your uri path.
I too have been trying to understand more about ContentUris as I had a section of code that wasn't working within the CalendarContract Instances table. This is strange because I didn't need to pass these in for the Calendars or Events table queries that I have developed.
So I added the appendId statements and passed in the current time in UTC for both values and the code now works. The actual query in my code is using the current time to looking for current events - please see the code below. If I take the appendID statements out an exception is raised - I think it was something like Content Provider URL not found.
String instanceQuery = "EVENT_ID = " + event_id +
" AND begin <= " + now +
" AND end >= " + now;
Uri.Builder eventsUriBuilder = CalendarContract.Instances.CONTENT_URI.buildUpon();
ContentUris.appendId(eventsUriBuilder, now);
ContentUris.appendId(eventsUriBuilder, now);
Uri eventsUri = eventsUriBuilder.build();
Cursor instanceCursor = null;
instanceCursor = ctx.getContentResolver().query(eventsUri,
new String[] { CalendarContract.Instances.EVENT_ID,
CalendarContract.Instances.BEGIN,
CalendarContract.Instances.END},
instanceQuery,
null,
null);
My code is working but I would like to know what impact the appendID statements actually have, e.g. do the values add any constraints. It looks like my actual query is overriding any implied range that is passed in and I really don't understand why they are required.
Hopefully a brief explanation from someone who understands this more would benefit the developer community....
What I want: I want to add calendar events in Android 2.2.
What I Have: I have added an event using the below code
Uri calendars = Uri.parse("content://com.android.calendar/events");
Cursor managedCursor = managedQuery(calendars, null, null, null, null);
startManagingCursor(managedCursor);
managedCursor.moveToFirst();
String ID = null;
do
{
ID = managedCursor.getString(managedCursor.getColumnIndexOrThrow("_id"));
}
while (managedCursor.moveToNext());
managedCursor.close();
int NewID = Integer.parseInt(ID) + 1;
ContentValues event = new ContentValues();
event.put("calendar_id", NewID); // --- Some confusion Here with the ID,
// --- not sure how to use it here
event.put("title", "New Event Title");
event.put("description", "Event Desc");
event.put("eventLocation", "Somewhere");
long startTime = System.currentTimeMillis() + 1000 * 60 * 60;
long endTime = System.currentTimeMillis() + 1000 * 60 * 60 * 2;
event.put("dtstart", startTime);
event.put("dtend", endTime);
event.put("allDay", 0); // 0 for false, 1 for true
event.put("eventStatus", 1);
event.put("visibility", 0);
event.put("transparency", 0);
event.put("hasAlarm", 0); // 0 for false, 1 for true
Uri eventsUri = Uri.parse("content://com.android.calendar/events");
Uri insertedUri = getContentResolver().insert(eventsUri, event);
What is the problem:
So far I have been successful in adding a single event on the specified date time, and apparently NewID's role is suspicious to me. When I try to add some other event, I get the returned Uri insertedUri and it shows me the newly added ID at the end of the URI. But I cant see any such event on the device. May be there is some problem in my understanding of the Calendar and events, or differences in both and their ID's. Kindly guide me what I am missing or doing wrong.
Regards,
Khawar
Most of the code is fine, you just need to know a little bit of concepts regarding calendar. Actually there is more than one calendar types in Android.
To Traverse all the calendars, Use following Uri for 2.2:
Uri calendars = Uri.parse("content://com.android.calendar"+ "/calendars");
And get the values of 'id' and 'name', you will get the idea.
NewID's role is suspicious to me
Your insertion code is fine, you just need to give the id of that calendar in which you want to insert any event.
I still believe that even myself needs to learn alot so if you have anything to tell or correct, you are most welcome. Following links helped me:
Working with Android Calendars
Accessing Calendars events without using gdata api