I can create a new Event in calendar, but I can't set the datetime of the event.
I can set the Location, title, description and so on.
When debugging, I can see the variables dtStart and dtEnd corretly (for testing, I'm using the string "15/05/2016 15:00:00" in the format dd/MM/yyyy hh:mm:ss - brasilian pattern)
Thank you for your help!
btnAdicionarAgenda.Click += delegate
{
Intent calIntent = new Intent(Intent.ActionInsert);
calIntent.SetData(CalendarContract.Events.ContentUri);
calIntent.SetType("vnd.android.cursor.item/event");
calIntent.PutExtra(CalendarContract.Events.InterfaceConsts.Title, calendarTitle);
calIntent.PutExtra(CalendarContract.Events.InterfaceConsts.Description, calendarDescription);
DateTime dtStart = DateTime.ParseExact(retNotificacao.get("dt_evento"), "dd/MM/yyyy HH:mm:ss",
System.Globalization.CultureInfo.InvariantCulture);
DateTime dtEnd = dtStart.AddHours(1);
long lDtStart = Utils.GetDateTimeMS(dtStart.Year, dtStart.Month, dtStart.Day, dtStart.Hour, dtStart.Minute);
long lDtEnd = Utils.GetDateTimeMS(dtEnd.Year, dtEnd.Month, dtEnd.Day, dtEnd.Hour, dtEnd.Minute);
calIntent.PutExtra(CalendarContract.Events.InterfaceConsts.Dtstart, lDtStart);
calIntent.PutExtra(CalendarContract.Events.InterfaceConsts.Dtend, lDtEnd);
calIntent.PutExtra(CalendarContract.Events.InterfaceConsts.EventTimezone, "UTC");
calIntent.PutExtra(CalendarContract.Events.InterfaceConsts.EventEndTimezone, "UTC");
calIntent.PutExtra(CalendarContract.Events.InterfaceConsts.EventLocation, Session.nmEscolaAluno);
StartActivity(calIntent);
};
Utils.cs:
public static long GetDateTimeMS(int yr, int month, int day, int hr, int min)
{
Calendar c = Calendar.GetInstance(Java.Util.TimeZone.Default);
c.Set(Calendar.DayOfMonth, day);
c.Set(Calendar.HourOfDay, hr);
c.Set(Calendar.Minute, min);
c.Set(Calendar.Month, month);
c.Set(Calendar.Year, yr);
return c.TimeInMillis;
}
Do NOT use Dtstart and Dtend, the documentation and examples that are posted (Google's and Xamarin's) are just wrong.
The string consts should be "EXTRA_EVENT_BEGIN_TIME" and "EXTRA_EVENT_END_TIME".
Change:
calIntent.PutExtra(CalendarContract.Events.InterfaceConsts.Dtstart, lDtStart);
calIntent.PutExtra(CalendarContract.Events.InterfaceConsts.Dtend, lDtEnd);
To:
calIntent.PutExtra(CalendarContract.ExtraEventBeginTime, lDtStart);
calIntent.PutExtra(CalendarContract.ExtraEventEndTime, lDtEnd);
Results of "15/05/2016 15:00:00" (plus one hour):
Start msec: 1466028054652
End msec: 1466031654659
Screen cap of event created:
Related
I'm new here so bare a bit with me. And yes i tried to google my question but really wasn't shure about the answers i found either.
So here's my problem:
I want to build an App where the User can select a Times from clicking different Buttons, and then calculate the Timedifference between.
The ButtonClick opens the TimePicker Dialog and the Examplecode i found on Microsoft Docs uses always the actual time. What i want is to use the last valid time from parsing the Buttontext. But i have no idea how to pass the ID of the senderbutton to the TimePicker class.
Here's the Eventhandler from the Button:
void TimeSelectOnClick (object sender, EventArgs eventArgs)
{
// Instantiate a TimePickerFragment (defined below)
TimePickerFragment frag = TimePickerFragment.NewInstance (
// Create and pass in a delegate that updates the Activity time display
// with the passed-in time value:
delegate (DateTime time)
{
timeSelectButton.Text = time.ToString("HH:mm");
});
// Launch the TimePicker dialog fragment (defined below):
frag.Show(FragmentManager, TimePickerFragment.TAG);
}
and here's the TimePicker dialog fragment:
// TimePicker dialog fragment
public class TimePickerFragment : DialogFragment, TimePickerDialog.IOnTimeSetListener
{
// TAG used for logging
public static readonly string TAG = "MyTimePickerFragment";
// Initialize handler to an empty delegate to prevent null reference exceptions:
Action<DateTime> timeSelectedHandler = delegate { };
// Factory method used to create a new TimePickerFragment:
public static TimePickerFragment NewInstance(Action<DateTime> onTimeSelected)
{
// Instantiate a new TimePickerFragment:
TimePickerFragment frag = new TimePickerFragment();
// Set its event handler to the passed-in delegate:
frag.timeSelectedHandler = onTimeSelected;
// Return the new TimePickerFragment:
return frag;
}
// Create and return a TimePickerDemo:
public override Dialog OnCreateDialog (Bundle savedInstanceState)
{
//Set the TimePicker default time
//Here i Want to parse the time from the button something like DateTime.Parse(buttonID.Text);
//Either with current time or parsed time... how to pass values from the sender button i have no idea
DateTime currentTime = DateTime.Parse("06:00");
// force 24-hour time format:
bool is24HourFormat = true;
// Instantiate a new TimePickerDemo, passing in the handler, the current
// time to display, and whether or not to use 24 hour format:
TimePickerDialog dialog = new TimePickerDialog
(Activity, this, currentTime.Hour, currentTime.Minute, is24HourFormat);
// Return the created TimePickerDemo:
return dialog;
}
// Called when the user sets the time in the TimePicker:
public void OnTimeSet(TimePicker view, int hourOfDay, int minute)
{
// Get the current time:
DateTime currentTime = DateTime.Now;
// Create a DateTime that contains today's date and the time selected by the user:
DateTime selectedTime = new DateTime(currentTime.Year, currentTime.Month, currentTime.Day, hourOfDay, minute, 0);
// Log the date and selected time:
Log.Debug(TAG, selectedTime.ToLongTimeString());
// Invoke the handler to update the Activity's time display to the selected time:
timeSelectedHandler (selectedTime);
}
}
thanks in advance to anybody here on Stackoverflow! You guys really do a great Job!
Cheers
You could add a property in TimePickerFragment
static string TimeString;
public static TimePickerFragment NewInstance(Action<DateTime> onTimeSelected,string time)
{
// Instantiate a new TimePickerFragment:
TimePickerFragment frag = new TimePickerFragment();
// Set its event handler to the passed-in delegate:
frag.timeSelectedHandler = onTimeSelected;
TimeString = time;
// Return the new TimePickerFragment:
return frag;
}
in Activity
TimePickerFragment frag = TimePickerFragment.NewInstance (
// Create and pass in a delegate that updates the Activity time display
// with the passed-in time value:
delegate (DateTime time)
{
timeSelectButton.Text = time.ToString("HH:mm");
},buttonID.Text);
And you can modify it in any place
TimePickerFragment.TimeString = "xxx";
In NativeScript, there is the TimePicker, which one shows a time, but in 12-hour format. I have a problem, because in my database all of my times are saved in string (in format "23:59").
I canot set hour, e.g. 14.
I have an idea, to convert string with split(':') and changing period AM to PM, but i cannot see any usefull method to do that. Please, help.
You can use the native APIs to set the 24-hour format.
TimePicker in NativeScript is using UIDatePicker in iOS
and android.widget.TimePicker in Android
page.js
"use strict";
var application = require("application");
function onLoaded(args) {
var page = args.object;
var tPicker = page.getViewById("tPicker");
if (application.android) {
tPicker.android.setIs24HourView(java.lang.Boolean.TRUE);
tPicker.hour = 23;
tPicker.minute = 59;
}
else if (application.ios) {
// a bit hacky solution
// important set the country not the language for locale
var local = NSLocale.alloc().initWithLocaleIdentifier("NL");
tPicker.ios.locale = local;
tPicker.hour = 23;
tPicker.minute = 59;
}
}
exports.onLoaded = onLoaded;
page.xml
<TimePicker id="tPicker"></TimePicker>
I'm working on an islamic app that show hijri calendar and also applying events like adding a specific date, time, event title and subject of that date so I want that when the app starts and displays calendar then the events' dates have different color.
caldroidFragment.setCaldroidListener(new CaldroidListener() {
#SuppressWarnings("deprecation")
#Override
public void onSelectDate(Date date, View view) {
// TODO Auto-generated method stub
// caldroidFragment.setSelectedDates(date, date);
Calendar text=Calendar.getInstance();
text.clear();
// text.set(Calendar.);
int d=(int) date.getDate();
int m=(int) date.getMonth();
int y=(int) date.getYear();
text.set(Calendar.YEAR, y+1900);
text.set(Calendar.MONTH, m);
text.set(Calendar.DATE, d);
hijridate.setText(HijriCalendarDate.getSimpleDate(text, 0));
}
}
enter link description here
You should use setBackgroundDrawableForDates method of caldroid object and pass the map with dates as keys and Drawable as value. Something like this:
import android.graphics.drawable.ColorDrawable;
final Map<Date, Drawable> backgroundForDateMap = new HashMap<>();
final Calendar c = Calendar.getInstance();
// 1. date
c.set(2016, Calendar.MAY, 1);
backgroundForDateMap.put(c.getTime(), new ColorDrawable(Color.GREEN));
// 2. date
c.set(2016, Calendar.MAY, 2);
backgroundForDateMap.put(c.getTime(), new ColorDrawable(Color.YELLOW));
caldroidFragment.setBackgroundDrawableForDates(backgroundForDateMap);
I'm building an app that should- among other things, let the user capture a picture and then save the picture and other info (like location of where this picture was taken -using GPS of the phone and etc...) on a DataBase.
Im using a string to save the pictures to the DataBase. So far so good. My problem is that after the user has captured a picture I can not find the path of the picture anyWhere (in order to display it later to the user )
I know I can display the picture if I use a image and not a string but then I am not able to save it to the DB.
Also I used the picture string (which should be the path of the picture ) to be the primaryKey column in my table and if the string is null this will be a problem for sure.
After checking on the internet I found out that you cannot use the GeoCoordinateWatcher (for GPS) on the emulator so I had to use a random place.
This led me into thinking that a picture taken by the emulator may not have a path??
Part of my code: (the Event of the camera and the bottun that saves everyting to DB)
void c_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
MessageBox.Show(e.ChosenPhoto.Length.ToString());
//Code to display the photo on the page in an image control named myImage.
BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
bmp.SetSource(e.ChosenPhoto);
myImage.Source = bmp;//display the picture right after taking it. before saving to DB
p.UrlImage = bmp.UriSource.AbsolutePath;//Do not Work!
}
}
private void saveToDB_Click(object sender, RoutedEventArgs e)
{
p.Description = DesriptionList.SelectedValue.ToString();//description of the pic
p.Date = DateTime.Today;//date picture taken
GeoCoordinateWatcher myWatcher = new GeoCoordinateWatcher();
var myPosition = myWatcher.Position;
p.Location = myPosition.Location.Altitude+" "+myPosition.Location.Latitude;//do not work with emulator
p.Location = "Some Where Over The Rainbow";
MainPage.m._bl.addPic(p);//add pic to DB
MessageBox.Show("Added Successfully! :)");
NavigationService.Navigate(new Uri(#"/Intro.xaml", UriKind.Relative));//go to another page
}
}
my class:
[Table]
public class Picture
{
public Picture()
{
}
public Picture(string l, string d, string url, DateTime da)
{
Location = l;
Description = d;
UrlImage = url;
Date = da;
}
string location;
[Column]
public string Location
{
get { return location; }
set { location = value; }
}
string urlImage;
[Column (IsPrimaryKey=true)]
public string UrlImage
{
get { return urlImage; }
set { urlImage = value; }
}
DateTime date;
[Column]
public DateTime Date
{
get { return date; }
set { date = value; }
}
string description;
[Column]
public string Description
{
get { return description; }
set { description = value; }
}
}
}
Anyway- I would like to know if I can get the path in some way...
And also- if I cant get the path- does Windows have a "Better" emulator?
this emulator cant do much and this is quite annoying giving the fact I dont have a WP to check my apps on..
Thanks!
You already get the stream of the taken image in e.ChosenPhoto. You just need to save that.
var imageBytes = new byte[e.ChosenPhoto.Length];
e.ChosenPhoto.Read(imageBytes, 0, imageBytes.Length);
using (var isoFile = IsolatedStorageFile.GetUserStoreForApplication()) {
using (var stream = isoFile.CreateFile("myImage.jpg")) {
stream.Write(imageBytes, 0, imageBytes.Length);
}
}
edit:
Regarding emulator, there is nothing wrong or limited about it.
The taken image is stored in a temp file that may vanish later on that's why you need to save it locally in your isolated storage if you want to display that image again.
Regarding GPS, you can use the additional tools (just click on the '>>' button on the right side of the emulator to set various settings that you find on an actual device such as accelerometer, location, network, etc.. For GeoWatcher you can define a set of points on the map that will be played back as if the device's actual GPS location was changing.
I'm wondering if some of you could offer advise on this.
I'm trying to change the NSDatePicker's step size to another value than 1.
On top of that I found that stepping minutes doesn't change the hours, nor the day.
I am using the delegate method datePickerCell:validateProposedDateValue:timeInterval:.
Now, though it does work as expected, the whole thing looks so much blown up that I started wondering if there is an easier way to accomplish this.
Any advise or direction for documentation is appreciated. Thank you.
Here's my code:
- (void)datePickerCell:(NSDatePickerCell *)aDatePickerCell validateProposedDateValue:(NSDate **)proposedDateValue
timeInterval:(NSTimeInterval *)proposedTimeInterval {
DLog(#"date picker for: %#", [aDatePickerCell identifier]);
NSDate *newProposedDateValue = nil;
// just in case that we don't need a correction
NSDate *correctedProposedDateValue = *proposedDateValue;
// the interval that the step generates
// > 0 means: the old date is later than the new proposed date
// < 0 means: the old date is earlier than the new proposed date
int interval = [[self dateValue] timeIntervalSinceDate:*proposedDateValue];
// define expected interval values for our scenarios
// we don't care about a minute step that does not cross the hour here
// nor do we care about an hour step that does not cross the day
// minutes are stepped: minute is stepped but hour remains (01:59 <-> 01:00), so the difference is 59 minutes
int const minuteSteppedUpAcrossHour = -59 *60;
int const minuteSteppedDownAcrossHour = - minuteSteppedUpAcrossHour;
// nor do we care about an hour step that does not cross the day
// hours are stepped: hour is stepped but day remains (10.03.13 00:30 <-> 10.03.13 23:30) we have a difference of 23 hours
int const hourSteppedUpAcrossDay = -23 *60 *60;
int const hourSteppedDownAcrossDay = - hourSteppedUpAcrossDay;
// define correction values for our scenarios
int const anHour = 60 *60;
int const aDay = anHour *24;
switch (interval) {
case hourSteppedUpAcrossDay:
correctedProposedDateValue = [*proposedDateValue dateByAddingTimeInterval:(-aDay)];
break;
case minuteSteppedDownAcrossHour:
correctedProposedDateValue = [*proposedDateValue dateByAddingTimeInterval:(+anHour)];
break;
case hourSteppedDownAcrossDay:
correctedProposedDateValue = [*proposedDateValue dateByAddingTimeInterval:(+aDay)];
break;
case minuteSteppedUpAcrossHour:
correctedProposedDateValue = [*proposedDateValue dateByAddingTimeInterval:(-anHour)];
break;
default:
break;
}
if ([self dateValue] < correctedProposedDateValue) {
newProposedDateValue = [self roundDateUpForMinuteIntervalConstraint:correctedProposedDateValue];
} else {
newProposedDateValue = [self roundDateDownForMinuteIntervalConstraint:correctedProposedDateValue];
}
*proposedDateValue = newProposedDateValue;
}
- (NSDate *)roundDateUpForMinuteIntervalConstraint:(NSDate *)date {
return [self date:date roundedUpToMinutes:MINUTE_INTERVAL_CONSTRAINT_FOR_SESSIONS_START];
}
- (NSDate *)roundDateDownForMinuteIntervalConstraint:(NSDate *)date {
return [self date:date roundedDownToMinutes:MINUTE_INTERVAL_CONSTRAINT_FOR_SESSIONS_START];
}
- (NSDate *)date:(NSDate *)date roundedUpToMinutes:(int)minutes {
// Strip miliseconds by converting to int
int referenceTimeInterval = (int)[date timeIntervalSinceReferenceDate];
int remainingSeconds = referenceTimeInterval %(60 *minutes);
int timeRoundedUpToMinutes = 0;
if (remainingSeconds== 0) {
timeRoundedUpToMinutes = referenceTimeInterval;
} else {
timeRoundedUpToMinutes = referenceTimeInterval -remainingSeconds +(60 *minutes);
}
return [NSDate dateWithTimeIntervalSinceReferenceDate:(NSTimeInterval)timeRoundedUpToMinutes];
}
- (NSDate *)date:(NSDate *)date roundedDownToMinutes:(int)minutes {
// Strip miliseconds by converting to int
int referenceTimeInterval = (int)[date timeIntervalSinceReferenceDate];
int remainingSeconds = referenceTimeInterval %(60 *minutes);
int timeRoundedUpToMinutes = referenceTimeInterval -remainingSeconds;
return [NSDate dateWithTimeIntervalSinceReferenceDate:(NSTimeInterval)timeRoundedUpToMinutes];
}