when class SettingsPage
included only InitializeComponent();
, the navigation method worked fine. But when I add some method (below) in class SettingsPage
, now It`s returns null.
Bulid and rebuild returns no errors and exceptions.
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private async void Button_Clicked(object sender, EventArgs e)
{
await this.Navigation.PushModalAsync(new SettingsPage()).ConfigureAwait(false); //Returns Null
}
}
this is my SettingsPage
class :
public partial class SettingsPage : ContentPage
{
readonly INotificationManager notificationManager;
DateTime _triggerTime;
public SettingsPage()
{
InitializeComponent();
Device.StartTimer(TimeSpan.FromSeconds(1), OnTimerTick);
notificationManager = DependencyService.Get<INotificationManager>();
notificationManager.NotificationReceived += (sender, eventArgs) =>
{
var evtData = (NotificationEventArgs)eventArgs;
ShowNotification(evtData.Title, evtData.Message);
};
}
bool OnTimerTick()
{
if (DateTime.Now >= _triggerTime)
{
_switch.IsToggled = false;
DisplayAlert("Alert", " It`s time to drink water :) ", "OK");
string title = $"Drink Water Reminder";
string message = $" It`s time to drink water :) ";
notificationManager.ScheduleNotification(title, message);
if (_switchVibrate.IsToggled)
{
// Use default vibration length
Vibration.Vibrate();
// Or use specified time
var duration = TimeSpan.FromSeconds(1);
Vibration.Vibrate(duration);
}
}
return true;
}
void OnTimePickerPropertyChanged(object sender, PropertyChangedEventArgs args)
{
if (args.PropertyName == "Time")
{
SetTriggerTime();
}
}
void OnSwitchToggled(object sender, ToggledEventArgs args)
{
SetTriggerTime();
}
void SetTriggerTime()
{
if (_switch.IsToggled)
{
_triggerTime = DateTime.Today + _timePicker.Time;
if (_triggerTime < DateTime.Now)
{
_triggerTime += TimeSpan.FromDays(1);
}
}
}
void ShowNotification(string title, string message)
{
Device.BeginInvokeOnMainThread(() =>
{
var msg = new Label()
{
Text = $"Notification Received:\nTitle: {title}\nMessage: {message}"
};
});
}
private void Button_Clicked(object sender, EventArgs e)
{
OnTimerTick();
}
}
As Jason mentioned, your code in the SettingsPage is causing the exception. If you take a look at your code, and start from the Constructor, you will notice that this line is called before _triggerTime is initialized:
if (DateTime.Now >= _triggerTime)
Hence you are referencing a variable that is null, which is causing an exception. One way to solve this would be to add a check before that line:
if (_triggerTime == null)
return false;
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다