<SearchBar Grid.Row="0" Grid.Column="1" HorizontalOptions="StartAndExpand" HorizontalTextAlignment="Start"
x:Name="VendorSearch"
FontSize="25"
BackgroundColor="{StaticResource TextWhiteColor}"
Placeholder="Search Vendor Name"
Text="{Binding VendorSearchText, Mode=TwoWay}"
TextChanged="VendorSearch_TextChanged"
VerticalOptions="Center"
WidthRequest="400" HeightRequest="50" />
void VendorSearch_TextChanged(System.Object sender, Xamarin.Forms.TextChangedEventArgs e)
{
try
{
SearchBar sb = (SearchBar)sender;
if (!string.IsNullOrEmpty(sb.Text))
{
vm = (VM)this.BindingContext?.DataContext;
if (vm != null)
{
vm.VendorSearchCommand.Execute(sb.Text.Trim());
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error {0}", ex.StackTrace);
}
}
Xamarin Forms App Crashes when we click on the 'x' button to clear text .. Why ??
All Null checks are in place but still it crashes
Related
I use Rg.Plugins.Popup in my Xamarin Forms app. This is working on Android but I have issue on iOS.
This is my control(base on PopupPage):
<pages:PopupPage
BackgroundColor="White"
x:Class="MyApp.Controls.PopupAlert"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:pages="http://rotorgames.com"
Padding="50,10">
<Frame
BackgroundColor="White"
CornerRadius="25"
HeightRequest="150"
VerticalOptions="Center"
WidthRequest="200">
<StackLayout>
<Label
FontAttributes="Bold"
FontSize="Title"
HorizontalOptions="Center"
HorizontalTextAlignment="Center"
Text="MyApp"
TextColor="Black" />
<Label
x:Name="LblMes"
Margin="0,5"
FontSize="Subtitle"
HorizontalOptions="CenterAndExpand"
TextColor="Black"
HorizontalTextAlignment="Center"
VerticalOptions="CenterAndExpand" />
<BoxView Style="{StaticResource Separator}" />
<Label
Margin="0,6,0,0"
FontAttributes="Bold"
FontSize="Subtitle"
HorizontalTextAlignment="Center"
HorizontalOptions="Center"
Text="OK"
TextColor="{StaticResource PrimaryColor}"
VerticalOptions="Center">
<Label.GestureRecognizers>
<TapGestureRecognizer Tapped="OkTapped" />
</Label.GestureRecognizers>
</Label>
</StackLayout>
</Frame>
</pages:PopupPage>
This is code:
public partial class PopupAlert
{
public PopupAlert()
{
InitializeComponent();
}
public void Init(String message)
{
LblMes.Text = message;
}
private async void OkTapped(object sender, EventArgs e)
{
await PopupNavigation.Instance.PopAsync();
}
}
I call my popup and I see it:
private readonly PopupAlert _popAlert = new PopupAlert();
private bool _isShow = false;
public async Task ShowMessage(string message)
{
//await App.Current.MainPage.DisplayAlert(AppRes.AppTitle, message, "Ok");
try
{
if (_isShow)
{
return;
}
_isShow = true;
_popAlert.Init(message);
await PopupNavigation.Instance.PushAsync(_popAlert);
}
finally
{
_isShow = false;
}
}
But I clicking button "Ok" I have exception:
StackTrace " at Rg.Plugins.Popup.IOS.Platform.PopupPlatformRenderer.PrefersStatusBarHidden ()
[0x00000] in
C:\\Users\\mhvdi\\Documents\\OpenSource\\Rg.Plugins.Popup\\Rg.Plugins.Popup\\Platforms\\Ios\\Platform\\PopupPlatformRenderer.cs:61 \n at (wrapper managed-to-native) UIKit.UIA…" string
This is my AppDelegate:
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
Rg.Plugins.Popup.Popup.Init();
global::Xamarin.Forms.Forms.Init();
....
}
How can I fix this issue?
1.I find the problem only happens in the latest version of Rg.Plugins.Popup 2.0.0.8.
2.Use a earlier version will work like 2.0.0.7.
3.An issue has been reported in the Github.
4.Check if the stack is empty before popping the stack:
if (Rg.Plugins.Popup.Services.PopupNavigation.Instance.PopupStack.Any())
{
await PopupNavigation.Instance.PopAsync();
}
I faced the same problem and it solved by get the latest version 2.0.0.9
I've created a custom renderer for Frame to feel like CardView in Android it works fine on Android P but i've tested on API 21,22,23 it doesn't have any kind of effect. Here is my Android Renderer.
public class ShadowFrameRenderer : Xamarin.Forms.Platform.Android.AppCompat.FrameRenderer
{
public ShadowFrameRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Frame> e)
{
base.OnElementChanged(e);
if (e.NewElement != null && e.NewElement is ShadowFrame)
{
Elevation = 30.0f;
TranslationZ = 0.0f;
SetZ(30f);
//this.SetBackgroundResource(Resource.Drawable.shadow);
//GradientDrawable drawable = (GradientDrawable)this.Background;
//drawable.SetColor(Android.Graphics.Color.ParseColor("#F0F0F0"));
}
UpdateElevation();
}
private void UpdateElevation()
{
//var materialFrame = (ShadowFrame)Element;
// we need to reset the StateListAnimator to override the setting of Elevation on touch down and release.
if(Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop)
Control.StateListAnimator = new Android.Animation.StateListAnimator();
// set the elevation manually
ViewCompat.SetElevation(this, 10);
ViewCompat.SetElevation(Control, 10);
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop)
{
Control.Elevation = 10;
Control.CardElevation = 10;
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
UpdateElevation();
//if (e.PropertyName == "Elevation")
//{
// UpdateElevation();
//}
}
}
Here is XAML.
<ContentPage.Content>
<controls:ShadowFrame Padding="10" Margin="10">
<Grid VerticalOptions="Start" HeightRequest="57" Margin="0,0,0,10" BackgroundColor="White">
<Grid ColumnSpacing="0" VerticalOptions="FillAndExpand">
<StackLayout BackgroundColor="{DynamicResource PMedium}"
x:Name="ListingLayoutB" VerticalOptions="FillAndExpand">
<Label Text="LISTING" HorizontalOptions="CenterAndExpand" TextColor="White" x:Name="ListingTxt"
FontSize="15" FontFamily="{StaticResource SBold}" VerticalOptions="CenterAndExpand"/>
</StackLayout>
<StackLayout Grid.Column="1" BackgroundColor="White" x:Name="DealsLayoutB" VerticalOptions="FillAndExpand">
<Label Text="DEALS" HorizontalOptions="CenterAndExpand" TextColor="{DynamicResource PMedium}" x:Name="DealsTxt"
FontSize="15" VerticalOptions="CenterAndExpand" FontFamily="{StaticResource SBold}"/>
</StackLayout>
</Grid>
</Grid>
</controls:ShadowFrame>
</ContentPage.Content>
And here is the result of above code. Screen shot taken from Android Emulator API level 23.
After setting BorderColor="White" the shadow is showing as expected.
Source: https://forums.xamarin.com/discussion/comment/416769#Comment_416769
In my xamarin.forms app, I have a listview with checkboxes for the selection of the individual cell. What I am trying to do is multi select the checkboxes inside the listview by providing a "select all" checkbox outside the listview.The Multiselection works fine. For the "select all" checkbox click and individual checkbox click, I am performing some actions like an API Call. The Problem I am facing is Whenever I Click on the "select all" checkbox, the checkbox changed event of individual checkbox gets triggered.I know its natural But is there any way to prevent it like subscribe or unsubscribe the changed event of individual checkbox or something?
Xaml
<Grid >
<Grid.RowDefinitions>
<RowDefinitions Height="Auto"/>
<RowDefinitions Height="Auto"/>
</Grid.RowDefinitions>
<StackLayout Grid.Row="0" Orientation="Horizontal">
<Label Text="Select All" FontSize="Micro" TextColor="LawnGreen" HorizontalOptions="Start" VerticalOptions="Center" >
</Label>
<CheckBox x:Name="MultiselectCheckbox" ScaleX="0.8" ScaleY="0.8" CheckedChanged="MultiSelectCheckBox_CheckedChanged" IsChecked="False" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" Color="LawnGreen"></CheckBox>
</StackLayout>
<ListView
x:Name="Listview"
HorizontalOptions="FillAndExpand"
ItemTapped="DistrictList_ItemTapped"
VerticalOptions="FillAndExpand" >
<ListView.ItemTemplate >
<DataTemplate >
<ViewCell >
<ViewCell.View>
<Frame HorizontalOptions="FillAndExpand">
<StackLayout Orientation="Horizontal" HorizontalOptions="FillAndExpand">
<Label Text="{Binding name}" FontSize="Micro" HorizontalOptions="StartAndExpand" VerticalOptions="Center" TextColor="Snow" Margin="5,0,0,0">
</Label>
<CheckBox CheckedChanged="Single_CheckedChanged" IsChecked="{Binding Selected}" Color="LightBlue" HorizontalOptions="End" >
</CheckBox>
</StackLayout>
</Frame>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
Multiselect Checkbox checked event
private void MultiSelectCheckBox_CheckedChanged(object sender, CheckedChangedEventArgs e)
{
if (!e.Value)
{
foreach (MyData TS in MyObject)
{
TS.Selected = false;
}
}
else{
foreach (MyData TS in MyObject)
{
TS.Selected = true;
}
PerformSomeAction();
}
}
Single selection Checkbox changed event
private void Single_CheckedChanged(object sender, CheckedChangedEventArgs e)
{
if (!e.Value)
{
}
else{
PerformSomeAction();
}
}
Data Model
public class MyData : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public string name { get; set; }
private bool selected;
public bool Selected
{
get
{
return selected;
}
set
{
if (value != null)
{
selected = value;
NotifyPropertyChanged("Selected");
}
}
}
}
Agree with # Nikhileshwar , you could define some properties to get the different condition .And since you had used MVVM, you would better put all logic handling in your viewmodel .
in xaml
<Grid >
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<StackLayout Grid.Row="0" Orientation="Horizontal" HeightRequest="40" BackgroundColor="LightPink">
<Label Text="Select All" FontSize="Micro" TextColor="Red" HorizontalOptions="Start" VerticalOptions="Center" >
</Label>
<CheckBox x:Name="MultiselectCheckbox" ScaleX="0.8" ScaleY="0.8" IsChecked="{Binding MultiselectCheck}" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" Color="Red"></CheckBox>
</StackLayout>
<ListView Grid.Row="1"
x:Name="Listview"
HorizontalOptions="FillAndExpand"
ItemsSource="{Binding MyItems}"
VerticalOptions="FillAndExpand" >
<ListView.ItemTemplate >
<DataTemplate >
<ViewCell >
<Frame Padding="0" HeightRequest="40" HorizontalOptions="FillAndExpand">
<StackLayout Orientation="Horizontal" HorizontalOptions="FillAndExpand">
<Label Text="{Binding name}" FontSize="Micro" HorizontalOptions="StartAndExpand" VerticalOptions="Center" TextColor="Red" Margin="5,0,0,0">
</Label>
<CheckBox IsChecked="{Binding Selected}" Color="Red" HorizontalOptions="End" >
</CheckBox>
</StackLayout>
</Frame>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
in ViewModel
public class MyViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
bool isMultiselect;
bool isSingleSelect;
public ObservableCollection<MyData> MyItems { get; set; }
private bool multiselectCheck;
public bool MultiselectCheck
{
get
{
return multiselectCheck;
}
set
{
if (multiselectCheck != value)
{
multiselectCheck = value;
if(!isSingleSelect)
{
isMultiselect = true;
foreach (MyData data in MyItems)
{
data.Selected = value;
}
isMultiselect = false;
}
NotifyPropertyChanged("MultiselectCheck");
}
}
}
public MyViewModel()
{
MyItems = new ObservableCollection<MyData>() {
new MyData(){name="Selection1" },
new MyData(){name="Selection2" },
new MyData(){name="Selection3" },
};
foreach(MyData data in MyItems)
{
data.PropertyChanged += Data_PropertyChanged;
}
}
I have a group of check boxes and i need them to change value.. if one is checked the other should be unchecked. The reason why dont want to implement MVVM is that this is just new frontend for already existing application, i just need these to work before we merge projects. This what i have and it doesnt work,i get null reference / System.NullReferenceException: 'Object reference not set to an instance of an object.'
I have this in my code
private void AdvancedCheckBox_IsCheckedChanged(object sender, IsCheckedChangedEventArgs e)
{
if (AdvancedCheckBox.IsChecked == true) //System.NullReferenceException: 'Object reference not set to an instance of an object.'
{
AllCheckBox.IsChecked = false;
UpperIntermediateCheckBox.IsChecked = false;
AdvancedCheckBox.IsChecked = false;
}
else
AdvancedCheckBox.IsChecked = true;
}
private void UpperIntermediateCheckBox_IsCheckedChanged(object sender, IsCheckedChangedEventArgs e)
{
if (UpperIntermediateCheckBox.IsChecked == true)
{
AllCheckBox.IsChecked = false;
UpperIntermediateCheckBox.IsChecked = false;
AdvancedCheckBox.IsChecked = false;
}
else
UpperIntermediateCheckBox.IsChecked = true;
}
private void IntermediateCheckBox_IsCheckedChanged(object sender, IsCheckedChangedEventArgs e)
{
CheckBox IntermediateCheckBox = sender as CheckBox;
if (IntermediateCheckBox.IsChecked == false)
{
AllCheckBox.IsChecked = false;
UpperIntermediateCheckBox.IsChecked = false;
AdvancedCheckBox.IsChecked = false ;
}
else
IntermediateCheckBox.IsChecked = true ;
}
private void AllCheckBox_IsCheckedChanged(object sender, IsCheckedChangedEventArgs e)
{
CheckBox AllCheckBox = sender as CheckBox;
if (AllCheckBox.IsChecked == true) System.NullReferenceException: 'Object reference not set to an instance of an object.'
{
UpperIntermediateCheckBox.IsChecked = false;
AdvancedCheckBox.IsChecked = false;
IntermediateCheckBox.IsChecked = false;
}
else
AllCheckBox.IsChecked = true;
}
and my xaml
<StackLayout Grid.Row="0"
Orientation="Horizontal"
Spacing="10"
HorizontalOptions="Start">
<grial:Checkbox x:Name="AllCheckBox"
IsCheckedChanged ="AllCheckBox_IsCheckedChanged"
HorizontalOptions="Start">
<Label
Margin="10,0"
FontSize="19"
Text="{ grial:Translate A_LabelAllArticles}"
VerticalOptions="Center"
TextColor="{ DynamicResource AccentColor }" />
</grial:Checkbox>
</StackLayout>
<StackLayout Grid.Row="1"
Orientation="Horizontal"
Spacing="10"
HorizontalOptions="Start">
<grial:Checkbox x:Name="BeginnerCheckBox"
IsChecked="false"
HorizontalOptions="Start">
<Label
FontSize="19"
Margin="10,0"
Text="{ grial:Translate A_LabelBeginnerArticles}"
VerticalOptions="Center"
TextColor="{ DynamicResource AccentColor }" />
</grial:Checkbox>
</StackLayout>
<StackLayout Grid.Row="2"
Orientation="Horizontal"
Spacing="10"
HorizontalOptions="Start">
<grial:Checkbox x:Name="IntermediateCheckBox"
IsCheckedChanged="IntermediateCheckBox_IsCheckedChanged"
HorizontalOptions="Start">
<Label
FontSize="19"
Margin="10,0"
Text="{ grial:Translate A_LabelIntermediateArticles}"
VerticalOptions="Center"
TextColor="{ DynamicResource AccentColor }" />
</grial:Checkbox>
</StackLayout>
<StackLayout Grid.Row="3"
Orientation="Horizontal"
Spacing="10"
HorizontalOptions="Start">
<grial:Checkbox x:Name="UpperIntermediateCheckBox"
IsCheckedChanged="UpperIntermediateCheckBox_IsCheckedChanged"
HorizontalOptions="Start">
<Label
FontSize="19"
Margin="10,0"
Text="{ grial:Translate A_LabelUpperIntermediateArticles}"
VerticalOptions="Center"
TextColor="{ DynamicResource AccentColor }" />
</grial:Checkbox>
</StackLayout>
<StackLayout Grid.Row="4"
Orientation="Horizontal"
Spacing="10"
HorizontalOptions="Start">
<grial:Checkbox x:Name="AdvancedCheckBox"
IsCheckedChanged="AdvancedCheckBox_IsCheckedChanged"
HorizontalOptions="Start">
<Label
FontSize="19"
Margin="10,0"
Text="{ grial:Translate A_LabelAdvancedArticles}"
VerticalOptions="Center"
TextColor="{ DynamicResource AccentColor }" />
</grial:Checkbox>
You are using a Checkbox from the Grial UIKit, but are defining the sender as the Native Xamarin.Forms CheckBox, use the Grial CheckBox as the Casting Class of the sender
//This will make every checkbox to checked or unchecked depending of the state of the clicked one
private void AllCheckBox_IsCheckedChanged(object sender, IsCheckedChangedEventArgs e)
{
CheckBox ClickedCheckbox = sender as UXDivers.Grial.Checkbox;
ChangeAllCheckboxesTo(ClickedCheckbox.IsChecked != null ? ClickedCheckbox.IsChecked : false);
}
//This will make every checkbox to false if you select one
private void AnyCheckBox_IsCheckedChanged(object sender, IsCheckedChangedEventArgs e)
{
CheckBox ClickedCheckbox = sender as UXDivers.Grial.Checkbox;
bool WasSelected = ClickedCheckbox.IsChecked != null ? ClickedCheckbox.IsChecked != null : false;
ChangeAllCheckboxesTo(false);
if(!WasSelected)
ClickedCheckbox.IsChecked = true;
}
public void ChangeAllCheckboxesTo(bool value)
{
try
{
UpperIntermediateCheckBox.IsChecked = value;
AdvancedCheckBox.IsChecked = value;
IntermediateCheckBox.IsChecked = value;
}
catch(Exception ex)
{
}
}
Hi tried to compile my app for the first time for IOS but I got this:
System.NullReferenceException: Object reference not set to an instance of an object
in the AppDelegate.
It stops in this line :return base.FinishedLaunching(app, options);
I'm relative new into xamarin so I am sorry for my unknowingness.
Here is my complete AppDelegate:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Globalization;
using System.IO;
using Flex;
using Foundation;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using System.Xml.Linq;
namespace dpsApp.iOS
{
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
Rg.Plugins.Popup.Popup.Init();
FlexButton.Init();
LoadApplication(new App());
return base.FinishedLaunching(app, options);
}
}
}
So here is my MainPage XAML:
`
<StackLayout WidthRequest="10000">
<StackLayout x:Name="LogoStack" BackgroundColor="White">
<Image x:Name="Image"
Source="a.png"
HeightRequest="120"
WidthRequest="120"
HorizontalOptions="Center">
<Image.GestureRecognizers>
<TapGestureRecognizer Tapped="EasterCount"/>
</Image.GestureRecognizers>
</Image>
</StackLayout>
<StackLayout x:Name="StackList" IsVisible="True" HeightRequest="3000">
<ListView x:Name="PageList"
HasUnevenRows="True"
ItemTapped="Link_ItemTapped"
HeightRequest="25"
BackgroundColor="White">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal" Margin="0,0,0,0" BackgroundColor="#e7e7e7" HeightRequest="65" Padding="0">
<Grid x:Name="DeleteStack" VerticalOptions="CenterAndExpand" BackgroundColor="White" HorizontalOptions="FillAndExpand" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="50" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="28" />
<RowDefinition Height="22" />
<RowDefinition Height="1" />
</Grid.RowDefinitions>
<Label Grid.Column="0" Grid.Row="0" Text="{Binding Title}" LineBreakMode="TailTruncation" FontSize="25" Margin="20,0,0,0"/>
<Label Grid.Column="0" Grid.Row="1" Text="{Binding Link}" LineBreakMode="TailTruncation" FontSize="17" Margin="20,0,0,0"/>
<Image Margin="0,0,20,0"
IsVisible="{Binding IsVisible}"
Grid.Column="1"
Grid.Row="0"
Grid.RowSpan="2"
x:Name="DeleteButton"
Source="delete.png"
VerticalOptions="Center"
HeightRequest="20"
HorizontalOptions="Center"/>
</Grid>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
<StackLayout x:Name="FirstTimeOpenStack" HorizontalOptions="Center">
<Label Text="Please tap on the plus icon in the top right corner to add a website" />
</StackLayout>
</StackLayout>
Your App Delegate looks ok. You have an unhandled exception somewhere in the App() you are launching.
Here is one way to capture unhandled exceptions:
namespace WiFiVisualPager.iOS
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
TaskScheduler.UnobservedTaskException += TaskSchedulerOnUnobservedTaskException;
global::Xamarin.Forms.Forms.Init();
DisplayCrashReport();
LoadApplication(new App());
return base.FinishedLaunching(app, options);
}
#region [Error handling]
//Credit: Peter Norman.
//https://peterno.wordpress.com/2015/04/15/unhandled-exception-handling-in-ios-and-android-with-xamarin/
//Minor compile fixes by David McCurley.
private static void TaskSchedulerOnUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs unobservedTaskExceptionEventArgs)
{
var newExc = new Exception("TaskSchedulerOnUnobservedTaskException", unobservedTaskExceptionEventArgs.Exception);
LogUnhandledException(newExc);
}
private static void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs)
{
var newExc = new Exception("CurrentDomainOnUnhandledException", unhandledExceptionEventArgs.ExceptionObject as Exception);
LogUnhandledException(newExc);
}
internal static void LogUnhandledException(Exception exception)
{
try
{
const string errorFileName = "Fatal.log";
var libraryPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Resources); // iOS: Environment.SpecialFolder.Resources
var errorFilePath = Path.Combine(libraryPath, errorFileName);
var errorMessage = String.Format("Time: {0}\r\nError: Unhandled Exception\r\n{1}",
DateTime.Now, exception.ToString());
File.WriteAllText(errorFilePath, errorMessage);
// Log to Android Device Logging.
//Android.Util.Log.Error("Crash Report", errorMessage);
}
catch
{
// just suppress any error logging exceptions
}
}
/// <summary>
// If there is an unhandled exception, the exception information is diplayed
// on screen the next time the app is started (only in debug configuration)
/// </summary>
[Conditional("DEBUG")]
private static void DisplayCrashReport()
{
const string errorFilename = "Fatal.log";
var libraryPath = Environment.GetFolderPath(Environment.SpecialFolder.Resources);
var errorFilePath = Path.Combine(libraryPath, errorFilename);
if (!File.Exists(errorFilePath))
{
return;
}
var errorText = File.ReadAllText(errorFilePath);
var alertView = new UIAlertView("Crash Report", errorText, null, "Close", "Clear") { UserInteractionEnabled = true };
alertView.Clicked += (sender, args) =>
{
if (args.ButtonIndex != 0)
{
File.Delete(errorFilePath);
}
};
alertView.Show();
}
#endregion
}
}