I' have a very strange issue with Xamarin.Forms.Maps.
I'm trying to implement a page with a map that get current location and move to region at page start.
All is working fine in IOS, but in Android, Geocoder & MoveToRegion are not working at all. Only the map is displayed.
I retrieve the location correctly (Long & Lat ) in the emulators & device.
MoveToRegion do nothing & GetAddressesForPositionAsync retrive nothing.
Here the information in my manifest :
<meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="mykey" />
<meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Here the code :
map.MoveToRegion(MapSpan.FromCenterAndRadius(
new Xamarin.Forms.Maps.Position(coordinates.Lat.Value, coordinates.Lng.Value), Distance.FromMiles(1))
);
var possibleAddresses = await locator.GetAddressesForPositionAsync(position);
I tried in Genymotion, Emulator from AVD.
I'm not able to test in real device ( The deployment fail in my tablet )
Edit :
global::Xamarin.Forms.Forms.Init(this, bundle);
Was correctly set but still not working.
I force geocoder usage and it thrown this error :
[MonoDroid] UNHANDLED EXCEPTION:
[MonoDroid] Java.IO.IOException: grpc failed
[MonoDroid] at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <896ad1d315ca4ba7b117efb8dacaedcf>:0
[MonoDroid] at Java.Interop.JniEnvironment+InstanceMethods.CallObjectMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args) [0x00069] in <6cd960837cc24c26bab2a0a29b597627>:0
[MonoDroid] at Java.Interop.JniPeerMembers+JniInstanceMethods.InvokeAbstractObjectMethod (System.String encodedMember, Java.Interop.IJavaPeerable self, Java.Interop.JniArgumentValue* parameters) [0x00014] in <6cd960837cc24c26bab2a0a29b597627>:0
[MonoDroid] at Android.Locations.Geocoder.GetFromLocationName (System.String locationName, System.Int32 maxResults) [0x0003c] in <d278c06ad5684d6882c743a94a93ebc2>:0
[MonoDroid] at Android.Locations.Geocoder+<>c__DisplayClass17_0.<GetFromLocationNameAsync>b__0 () [0x00000] in <d278c06ad5684d6882c743a94a93ebc2>:0
[MonoDroid] at System.Threading.Tasks.Task`1[TResult].InnerInvoke () [0x0000f] in <896ad1d315ca4ba7b117efb8dacaedcf>:0
[MonoDroid] at System.Threading.Tasks.Task.Execute () [0x00010] in <896ad1d315ca4ba7b117efb8dacaedcf>:0
[MonoDroid] --- End of stack trace from previous location where exception was thrown ---
[MonoDroid] at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <896ad1d315ca4ba7b117efb8dacaedcf>:0
[MonoDroid] at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <896ad1d315ca4ba7b117efb8dacaedcf>:0
[MonoDroid] at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <896ad1d315ca4ba7b117efb8dacaedcf>:0
[MonoDroid] at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <896ad1d315ca4ba7b117efb8dacaedcf>:0
[MonoDroid] at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in <896ad1d315ca4ba7b117efb8dacaedcf>:0
[MonoDroid] at Xamarin.Forms.Maps.Android.GeocoderBackend+<GetPositionsForAddressAsync>d__1.MoveNext () [0x0006b] in <39c694c022be4f7b8a39897d372b2d00>:0
[MonoDroid] --- End of stack trace from previous location where exception was thrown ---
[MonoDroid] at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <896ad1d315ca4ba7b117efb8dacaedcf>:0
[MonoDroid] at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <896ad1d315ca4ba7b117efb8dacaedcf>:0
[MonoDroid] at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <896ad1d315ca4ba7b117efb8dacaedcf>:0
[MonoDroid] at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <896ad1d315ca4ba7b117efb8dacaedcf>:0
[MonoDroid] at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in <896ad1d315ca4ba7b117efb8dacaedcf>:0
[MonoDroid] at Picaplant.Views.GeolocationPage+<HandleAdressCompleted>d__8.MoveNext () [0x00047] in /Users/OrcusZ/Documents/AutoEntrepreneur/Picaplant/Source/Picaplant/Views/GeolocationPage.xaml.cs:158
[MonoDroid] --- End of stack trace from previous location where exception was thrown ---
[MonoDroid] at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <896ad1d315ca4ba7b117efb8dacaedcf>:0
[MonoDroid] at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__6_0 (System.Object state) [0x00000] in <896ad1d315ca4ba7b117efb8dacaedcf>:0
[MonoDroid] at Android.App.SyncContext+<>c__DisplayClass2_0.<Post>b__0 () [0x00000] in <d278c06ad5684d6882c743a94a93ebc2>:0
[MonoDroid] at Java.Lang.Thread+RunnableImplementor.Run () [0x00008] in <d278c06ad5684d6882c743a94a93ebc2>:0
[MonoDroid] at Java.Lang.IRunnableInvoker.n_Run (System.IntPtr jnienv, System.IntPtr native__this) [0x00008] in <d278c06ad5684d6882c743a94a93ebc2>:0
[MonoDroid] at (wrapper dynamic-method) System.Object:6621ff63-14b8-4291-a222-45bff630bddc (intptr,intptr)
[MonoDroid] --- End of managed Java.IO.IOException stack trace ---
[MonoDroid] java.io.IOException: grpc failed
[MonoDroid] at android.location.Geocoder.getFromLocationName(Geocoder.java:178)
[MonoDroid]
EDIT 2 :
Same error with Xamarin Form Working with maps sample
Any idea ?
Here's a working cross-platform sample app. It runs in a KitKat 4.4 API Level 19 emulator and also in a Samsung Android device.
We also present a custom Geocoder implementation using HTTP requests given that the standard one works fine for an actual Android device but returns an empty response for the emulator.
XAML:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:Maps="clr-namespace:Xamarin.Forms.Maps;assembly=Xamarin.Forms.Maps.dll"
xmlns:local="clr-namespace:App20"
x:Class="App20.MainPage">
<ContentPage.Content>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="8*"></RowDefinition>
<RowDefinition Height="4*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Maps:Map x:Name="map1" Grid.Row="0"></Maps:Map>
<ListView ItemsSource="{Binding AddressList}" Grid.Row="1" />
<Button Text="Move To Region" Grid.Row="2" Clicked="Button_Clicked_Move"></Button>
<Button Text="Get Address" Grid.Row="3" Clicked="Button_Clicked_Address"></Button>
</Grid>
</ContentPage.Content>
</ContentPage>
CS:
public partial class MainPage : ContentPage
{
MyViewModel vm;
public MainPage()
{
InitializeComponent();
vm = new MyViewModel();
BindingContext = vm;
}
private void Button_Clicked_Move(object sender, EventArgs e)
{
map1.MoveToRegion(MapSpan.FromCenterAndRadius(
new Position(vm.Lat, vm.Lon), Distance.FromMiles(vm.Distance)));
}
private async void Button_Clicked_Address(object sender, EventArgs e)
{
Geocoder gc = new Geocoder();
var list = await gc.GetAddressesForPositionAsync(new Position(vm.Lat, vm.Lon));
if (list.Count() > 0)
{
foreach (string s in list)
vm.AddressList.Add(s);
}
else
{
MyGeocoder mgc = new MyGeocoder();
var mylist = await mgc.GetAddressesForPositionAsync(vm.Lat, vm.Lon, vm.Key);
foreach (string s in mylist)
vm.AddressList.Add(s);
}
}
}
View Model:
public class MyViewModel
{
public string Key { get; }
public double Lat { get; set; }
public double Lon { get; set; }
public double Distance { get; set; }
public ObservableCollection<string> AddressList { get; set; }
public MyViewModel()
{
Lat = 40.706501;
Lon = -74.011340;
Distance = 0.5;
Key = "YOUR_API_KEY";
AddressList = new ObservableCollection<string>();
}
}
Custom Geocoder:
public class MyGeocoder
{
public async Task<IEnumerable<string>> GetAddressesForPositionAsync(double lat, double lon, string key)
{
HttpClient client = new HttpClient();
var request = string.Format(#"https://maps.googleapis.com/maps/api/geocode/json?latlng={0},{1}&key={2}", lat, lon, key);
var json = await client.GetStringAsync(request);
var result = JObject.Parse(json)["results"];
List<string> list = new List<string>();
foreach (JToken jt in result)
list.Add((string)jt["formatted_address"]);
return list.AsEnumerable<string>();
}
}
Related
I am trying to use System.Text.Josn (5.0.1) which has internal dependency to System.Runtime.CompilerServices.Unsafe.dll Version=4.0.4.1.
Nuget has installed Version=5.0.0.0 of System.Runtime.CompilerServices.Unsafe.dll which cause the following runtime exception :
System.IO.FileNotFoundException
HResult=0x80070002
Message=Could not load file or assembly 'System.Runtime.CompilerServices.Unsafe, Version=4.0.4.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
Source=System.Memory
StackTrace:
at System.MemoryExtensions.AsSpan(String text)
at System.Text.Json.Serialization.Converters.StringConverter.Write(Utf8JsonWriter writer, String value, JsonSerializerOptions options)
at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
at System.Text.Json.Serialization.JsonConverter`1.WriteCore(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
at System.Text.Json.JsonSerializer.WriteCore[TValue](JsonConverter jsonConverter, Utf8JsonWriter writer, TValue& value, JsonSerializerOptions options, WriteStack& state)
at System.Text.Json.JsonSerializer.WriteCore[TValue](Utf8JsonWriter writer, TValue& value, Type inputType, JsonSerializerOptions options)
at System.Text.Json.JsonSerializer.WriteCoreBytes[TValue](TValue& value, Type inputType, JsonSerializerOptions options)
at System.Text.Json.JsonSerializer.SerializeToUtf8Bytes[TValue](TValue value, JsonSerializerOptions options)
I have 2 Questions :
1- Why Nuget install the wrong version of System.Runtime.CompilerServices.Unsafe
2- As i see Nuget installed upgraded version of System.Runtime.CompilerServices.Unsafe, which i am thinking it should work according to nuget description :
System.Text.Josn (5.0.1) needs System.Runtime.CompilerServices.Unsafe version at least Version=4.0.4.1, which means the upgraded ones should work too.
But it seems not
A Code example is posted bellow.
Client / Server Nuget dependencies :
<ItemGroup>
<PackageReference Include="Google.Protobuf">
<Version>3.19.1</Version>
</PackageReference>
<PackageReference Include="Grpc">
<Version>2.41.1</Version>
</PackageReference>
<PackageReference Include="Grpc.Tools">
<Version>2.41.1</Version>
</PackageReference>
<PackageReference Include="System.Text.Json">
<Version>5.0.1</Version>
</PackageReference>
</ItemGroup>
Grpc Client Code implementation
public class GrpcClient
{
public GrpcClient()
{
Channel channel = new Channel("localhost", 5001, ChannelCredentials.Insecure);
myClient = new ApiTest.ApiTestClient(channel);
}
public string UnaryCall()
{
var bytes = JsonSerializer.SerializeToUtf8Bytes("Hallo");
var request = new Request { Data = ByteString.CopyFrom(bytes) };
var response = myClient.SayHello(request);
var result = JsonSerializer.Deserialize<string>(response.ToByteArray());
return result;
}
private readonly ApiTest.ApiTestClient myClient;
}
Service Code Implementation
public class ApiTestServices : ApiTest.ApiTestBase
{
public override Task<Response> SayHello(Request request, ServerCallContext context)
{
var result = JsonSerializer.Deserialize<string>(request.Data.ToByteArray());
var bytes = JsonSerializer.SerializeToUtf8Bytes<string>(result + "Anas");
return Task.FromResult(new Response { Data = ByteString.CopyFrom(bytes) });
}
}
**Server Code Implementation**
public class GrpcService
{
public GrpcService()
{
var services = new List<ServerServiceDefinition> { ApiTest.BindService(new ApiTestServices()) };
var server = new global::Grpc.Core.Server
{
Ports = { new ServerPort("localhost", 5001, ServerCredentials.Insecure) }
};
services.ToList().ForEach(item => server.Services.Add(item));
server.Start();
}
}
Any help would be appreciated
Thanks
I'm attempting to serialize my logs to Json. I'm using log4net with a custom layout, but when an exception is logged, I get the following malformed JSON (Note the additional stacktrace info at the end)
Am I missing a setting for log4net, or is this a serialization issue?
UPDATE: This has to be something with log4net, because json.net serializes an Exception perfectly.
***UPDATE (FIXED): Updated code below.
{
"UserSessionId":"4b146c92-fe99-4f78-bbef-720df2cf7473",
"ProcessSessionId":1,
...
"Logger":"testharness.Program","ThreadName":"1",
"ExceptionObject":{
"ClassName":"System.ApplicationException",
"Message":"Test Exception Logging",
"Data":null,
"InnerException":null,
"HelpURL":null,
"StackTraceString":" at testharness.Program.Main(String[] args) in C:\\temp\\testharness\\Program.cs:line 18",
"RemoteStackTraceString":null,
...
"WatsonBuckets":null
},
...
"log4net:HostName":"ol-4RBNMH2"
}}
System.ApplicationException: Test Exception Logging
at testharness.Program.Main(String[] args) in C:\temp\testharness\Program.cs:line 18
log4net configuratiton
<log4net>
<appender name="RollingFileCompositeAppender" type="log4net.Appender.RollingFileAppender">
<file value="c:\\logs\\testharness.txt"/>
<appendToFile value="true"/>
<rollingStyle value="Composite"/>
<datePattern value="yyyy-MM-dd"/>
<maxSizeRollBackups value="-1"/>
<maximumFileSize value="1MB"/>
<countDirection value="1"/>
<preserveLogFileNameExtension value="false"/>
<staticLogFileName value="false"/>
<layout type="Company.log4net.JsonLayout"></layout>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="RollingFileCompositeAppender"/>
</root>
</log4net>
The Custom Layout class
public class JsonLayout : LayoutSkeleton
{
public JsonLayout() {
IgnoresException = false;
}
...
/// <inheritdoc />
public override void ActivateOptions()
{
}
/// <inheritdoc />
public override void Format(TextWriter writer, LoggingEvent loggingEvent)
{
_customProperties.PhysicalMemory = Process.GetCurrentProcess().WorkingSet64;
var evt = new CustomLoggingEvent(loggingEvent, _customProperties);
writer.Write(JsonConvert.SerializeObject(evt));
}
}
[JsonObject(MemberSerialization.OptIn)]
public class CustomLoggingEvent
{
...
[JsonProperty]
public Exception ExceptionObject { get; set; }
[JsonProperty]
public long PhysicalMemory { get; set; }
[JsonProperty]
public PropertiesDictionary Properties { get; set; }
}
The Test Harness:
internal class Program
{
private static void Main()
{
Console.WriteLine($"{typeof(JsonLayout)}");
var log = log4net.LogManager.GetLogger(typeof(Program));
try
{
log.Debug("hello again world");
throw new ApplicationException("Test Exception Logging");
}
catch (Exception e)
{
log.Error("Exception Thrown", e);
}
Console.ReadLine();
}
}
I downloaded the log4net source and found the issue. When creating a custom layout implementing LayoutSkeleton, if your layout handles the LoggingEvent.ExceptionObject, then the IgnoresException property should be set to false; the default value is true. I updated the code in the question with a constructor wherein the IgnoresException property is set to true. I probably should have waited a day while I researched, but maybe this will help someone else.
I'm using AWS mobile SDK for Xamarin (http://aws.amazon.com/about-aws/whats-new/2014/10/09/aws-mobile-sdk-for-xamarin-available-on-awslabs/) and i got a problem when i use GetObjectAsync() method to get files from my S3 Bucket. My code:
private async Task<string> GetObjectFromAmazonS3(S3Object s3Object, string fileContent, string bucketName)
{
AWSCredentials credential = new BasicAWSCredentials(Constants.S3AccessKey, Constants.S3SecretKey);
_amazonS3Client = new AmazonS3Client(credential, Amazon.RegionEndpoint.EUCentral1);
_amazonS3Client.ExceptionEvent += ClientExceptionHandler;
GetObjectRequest getObjectRequest = new GetObjectRequest
{
BucketName = bucketName,
Key = s3Object.Key
};
GetObjectResponse getObjectResponse = await _amazonS3Client.GetObjectAsync(getObjectRequest);
using (Stream responseStream = getObjectResponse.ResponseStream)
using (StreamReader reader = new StreamReader(responseStream))
{
fileContent = reader.ReadToEnd();
}
Logger.Log(Logger.Category.Debugging, "Download S3 Objects to the phone", "Get object " + s3Object.Key + " successfully");
return fileContent;
}
The problem is that when the application waiting for the response from GetObjectAsync() method, the phone is disconnected with the network then i got an exception:
2015-03-03T07:23:27.582Z,Debugging,UnhandledException(Android),Amazon.Runtime.AmazonServiceException: A WebException with status NameResolutionFailure was thrown.
---> System.Net.WebException: Error: NameResolutionFailure
==> at System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult) [0x00000] in <filename unknown>:0
==> at System.Threading.Tasks.TaskFactory`1[System.Net.WebResponse].InnerInvoke (System.Threading.Tasks.TaskCompletionSource`1 tcs, System.Func`2 endMethod, IAsyncResult l) [0x00000] in <filename unknown>:0
==> --- End of stack trace from previous location where exception was thrown ---
==> at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x00000] in <filename unknown>:0 ==> at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter[System.Net.WebResponse].GetResult () [0x00000] in <filename unknown>:0
And my application is crashed. I tried to handle the application by using ExceptionEvent but i still cannot catch this exception.
Is there any suggestion to solve this problem? (It's very terrible that the application crashes each time the wifi disconnected).
Sorry for the silly question.I even did not understand what should be given as title to this question.
I have 3 buttons and when I click them listboxes should be displayed.
And if I select an item in listbox it should be navigated and start playing.
When I click a button listbox is displaying and when an item is selected it is navigating to to other page and playing.After performing selection changed if I click any button I was getting error like
A first chance exception of type 'System.NullReferenceException' occurred in tori.dll
An unhandled exception of type 'System.NullReferenceException' occurred in tori.dll
Archieves .xaml:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,-951,0">
<Button Name="btn1" Click="btn1_Click" Content="Daily" HorizontalAlignment="Left" Margin="0,88,0,0" VerticalAlignment="Top" Width="127" Height="72"/>
<Button Name="btn2" Click="btn2_Click" Content="Weekly" HorizontalAlignment="Left" Margin="132,88,0,0" VerticalAlignment="Top" Height="72" Width="140"/>
<Button Name="btn3" Click="btn3_Click" Content="CurrentMonth" HorizontalAlignment="Left" Margin="277,88,0,0" VerticalAlignment="Top" Height="72" Width="169"/>
<ListBox x:Name="itemsList" Margin="0,225,945,0"
SelectionChanged="itemsList_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Height="130">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Image delay:LowProfileImageLoader.UriSource="{Binding ThumbnailUrl}"
Grid.Column="0"
Width="500"
Height="125"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Margin="6"/>
<StackPanel Margin="10,20,0,0"
Grid.Column="1"
Height="60"
Orientation="Horizontal"
VerticalAlignment="Center">
<TextBlock Text="{Binding title}"
FontSize="40" />
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
Archieves.xaml.cs:
namespace tori
{
public partial class Archieves : PhoneApplicationPage
{
public Archieves()
{
InitializeComponent();
}
private void btn1_Click(object sender, RoutedEventArgs e)
{
WebClient downloader = new WebClient();
Uri uri = new Uri(" http://www.toucheradio.com/RSSFeed/rssDaily.php ", UriKind.Absolute);
downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(ChannelDownloaded);
downloader.DownloadStringAsync(uri);
}
void ChannelDownloaded(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Result == null || e.Error != null)
{
MessageBox.Show("There was an error downloading the XML-file!");
}
else
{
// Deserialize if download succeeds
XDocument document = XDocument.Parse(e.Result);
var queue = from item in document.Descendants("item")
select new Item
{
title = item.Element("title").Value
,
link = item.Element("link").Value
,
pubDate = item.Element("pubDate").Value
,
ThumbnailUrl = item.Element(item.GetNamespaceOfPrefix("media") + "thumbnail").Attribute("url").Value
,
};
itemsList.ItemsSource = queue;
}
}
private void btn2_Click(object sender, RoutedEventArgs e)
{
WebClient downloader = new WebClient();
Uri uri = new Uri(" http://www.toucheradio.com/RSSFeed/rssWeekly.php ", UriKind.Absolute);
downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Channel1Downloaded);
downloader.DownloadStringAsync(uri);
}
void Channel1Downloaded(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Result == null || e.Error != null)
{
MessageBox.Show("There was an error downloading the XML-file!");
}
else
{
// Deserialize if download succeeds
XDocument document = XDocument.Parse(e.Result);
var queue = from item in document.Descendants("item")
select new Item
{
title = item.Element("title").Value
,
link = item.Element("link").Value
,
pubDate = item.Element("pubDate").Value
,
ThumbnailUrl = item.Element(item.GetNamespaceOfPrefix("media") + "thumbnail").Attribute("url").Value
,
};
itemsList.ItemsSource = queue;
}
}
private void btn3_Click(object sender, RoutedEventArgs e)
{
WebClient downloader = new WebClient();
Uri uri = new Uri("http://www.toucheradio.com/RSSFeed/rssMonthly.php ", UriKind.Absolute);
downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Channel2Downloaded);
downloader.DownloadStringAsync(uri);
}
void Channel2Downloaded(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Result == null || e.Error != null)
{
MessageBox.Show("There was an error downloading the XML-file!");
}
else
{
// Deserialize if download succeeds
XDocument document = XDocument.Parse(e.Result);
var queue = from item in document.Descendants("item")
select new Item
{
title = item.Element("title").Value
,
link = item.Element("link").Value
,
pubDate = item.Element("pubDate").Value
,
ThumbnailUrl = item.Element(item.GetNamespaceOfPrefix("media") + "thumbnail").Attribute("url").Value
,
};
itemsList.ItemsSource = queue;
}
}
private void itemsList_SelectionChanged(Object sender, SelectionChangedEventArgs e)
{
var app = App.Current as App;
app.selectedItem = (Item)itemsList.SelectedItem;
this.NavigationService.Navigate(new Uri("/Details.xaml", UriKind.Relative));
}
Item.cs:
namespace tori
{
public class Item
{
public string title { get; set; }
public string ThumbnailUrl { get; set; }
public string link { get; set; }
public string pubDate { get; set; }
}
}
Details.xaml:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid Height="617" VerticalAlignment="Top" Margin="-27,96,0,0">
<Image x:Name="ThumbnailUrl"
Width="279"
Height="421"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Margin="0,-29,204,225" />
<Image x:Name="Image1" Tap="Image1_Tap" Margin="46,430,354,92" Source="/Images/pausebutton.png"/>
<TextBlock x:Name="title" FontSize="30" TextWrapping="Wrap" Margin="284,57,-50,436" />
<TextBlock x:Name="pubDate" FontSize="25" Margin="284,186,10,363" />
<MediaElement x:Name="MediaElement1" AutoPlay="True" Margin="0,397,20,0" Height="94" VerticalAlignment="Top" />
Details.xaml.cs:
namespace tori
{
public partial class Details : PhoneApplicationPage
{
Item item;
public Details()
{
InitializeComponent();
var app = App.Current as App;
item = app.selectedItem;
title.Text = item.title;
pubDate.Text = item.pubDate;
ThumbnailUrl.Source = new BitmapImage(new Uri(item.ThumbnailUrl, UriKind.RelativeOrAbsolute));
string s = item.link;
string url = s.Replace("archivesplayer", "hostArchivesURLForMobile");
WebClient downloader = new WebClient();
Uri uri = new Uri(url,UriKind.Absolute);
downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Channel3Downloaded);
downloader.DownloadStringAsync(uri);
}
void Channel3Downloaded(object sender, DownloadStringCompletedEventArgs e)
{
var textData = (string)e.Result;
Regex urlRegex = new Regex("<td height=\"25\" align=\"center\">(?<url>.*)</td>");
MatchCollection mc = urlRegex.Matches(textData);
string url = "";
if (mc.Count > 0)
{
url = mc[0].Groups["url"].Value;
MediaElement1.Source = new Uri(url, UriKind.Absolute);
MediaElement1.Play();
}
}
}
}
After performing selecting item if I click a button I was getting error in this line
title.Text = item.title;
Can anybody please tell me how can I overcome this null exception.When I click on a button selection changed event is raising instead of click event. I am unable to know the reason for this.
Please anybody help me with this.
many Thanks in advance.
When you change the ItemsSource, the SelectionChanged event is raised. I think whenever you change the ItemsSource, the selection is reset (that is - set to null (none selected)). And that's how it should be, otherwise an item that's not in the ItemsSource could be the SelectedItem which is just wrong.
Now, to fix your issue, just check if SelectedItem != null in itemsList_SelectionChanged method.
Something else about your code: the methods btn1_Click, btn2_Click and btn3_Click seem to only have minor differences, so you could put most of the code in one method and just pass it the url. That's even more important for the ChannelDownloaded methods (as they are much longer). Basically you want to reuse code as much as possible. That makes the code easier to read (as it's not 10 pages, but one, so to speak), and easier to maintain (if there's an error - you only need to fix it in one place).
Since updating to version 3.0.1 of MonoDevelop, I've been unable to work with layout files. When I create a new layout file and then try to edit it from the "Source" tab, I get the following error:
System.InvalidOperationException: Layout not yet loaded
at Xamarin.AndroidDesigner.DesignerSession.SetLayoutXml (System.String xml, Boolean allowUndo) [0x000bf] in /Users/builder/data/lanes/monodevelop-mac-3.0.1/6642975f/source/md-addins/MonoDevelop.MonoDroid/Xamarin.AndroidDesigner/Xamarin.AndroidDesigner/DesignerSession.cs:353
at MonoDevelop.MonoDroid.Gui.LayoutSourceEditorView.SaveContent () [0x00025] in /Users/builder/data/lanes/monodevelop-mac-3.0.1/6642975f/source/md-addins/MonoDevelop.MonoDroid/MonoDevelop.MonoDroid/Gui/AndroidDesignerView.cs:641
at MonoDevelop.MonoDroid.Gui.LayoutSourceEditorView.Deselected () [0x00000] in /Users/builder/data/lanes/monodevelop-mac-3.0.1/6642975f/source/md-addins/MonoDevelop.MonoDroid/MonoDevelop.MonoDroid/Gui/AndroidDesignerView.cs:670
at MonoDevelop.Ide.Gui.SdiWorkspaceWindow.SetCurrentView (Int32 newIndex) [0x00032] in /Users/builder/data/lanes/monodevelop-mac-3.0.1/6642975f/source/monodevelop/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui/SdiWorkspaceWindow.cs:571
at MonoDevelop.Ide.Gui.SdiWorkspaceWindow+<AddButton>c__AnonStoreyB0.<>m__169 (System.Object sender, System.EventArgs e) [0x00033] in /Users/builder/data/lanes/monodevelop-mac-3.0.1/6642975f/source/monodevelop/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui/SdiWorkspaceWindow.cs:488
at MonoDevelop.Components.Tab.OnActivated (System.EventArgs e) [0x0000d] in /Users/builder/data/lanes/monodevelop-mac-3.0.1/6642975f/source/monodevelop/main/src/core/MonoDevelop.Ide/MonoDevelop.Components/Tabstrip.cs:396
at MonoDevelop.Components.Tab.Activate () [0x00000] in /Users/builder/data/lanes/monodevelop-mac-3.0.1/6642975f/source/monodevelop/main/src/core/MonoDevelop.Ide/MonoDevelop.Components/Tabstrip.cs:244
at MonoDevelop.Ide.Gui.SdiWorkspaceWindow.ActiveDocumentChanged (System.Object sender, System.EventArgs e) [0x0000b] in /Users/builder/data/lanes/monodevelop-mac-3.0.1/6642975f/source/monodevelop/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui/SdiWorkspaceWindow.cs:501
at (wrapper delegate-invoke) <Module>:invoke_void__this___object_EventArgs (object,System.EventArgs)
at (wrapper delegate-invoke) <Module>:invoke_void__this___object_EventArgs (object,System.EventArgs)
at (wrapper delegate-invoke) <Module>:invoke_void__this___object_EventArgs (object,System.EventArgs)
at (wrapper delegate-invoke) <Module>:invoke_void__this___object_EventArgs (object,System.EventArgs)
at (wrapper delegate-invoke) <Module>:invoke_void__this___object_EventArgs (object,System.EventArgs)
at (wrapper delegate-invoke) <Module>:invoke_void__this___object_EventArgs (object,System.EventArgs)
at (wrapper delegate-invoke) <Module>:invoke_void__this___object_EventArgs (object,System.EventArgs)
at MonoDevelop.Ide.Gui.Workbench.OnDocumentChanged (System.Object s, System.EventArgs a) [0x0000b] in /Users/builder/data/lanes/monodevelop-mac-3.0.1/6642975f/source/monodevelop/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui/Workbench.cs:606
at MonoDevelop.Ide.Gui.DefaultWorkbench.OnActiveWindowChanged (System.Object sender, System.EventArgs e) [0x00075] in /Users/builder/data/lanes/monodevelop-mac-3.0.1/6642975f/source/monodevelop/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui/DefaultWorkbench.cs:749
at Gtk.Notebook.SwitchPageSignalCallback (IntPtr arg0, IntPtr arg1, UInt32 arg2, IntPtr gch) [0x00000] in <filename unknown>:0
I haven't found a bug indicating others are experiencing this. Could it be a configuration issue of some sort in my environment? I'm using Mono for Android 4.2.1.196198126.
This issue was addressed in version 3.0.2 of MonoDevelop.
http://monodevelop.com/Download/Release_Notes/Release_Notes_for_MonoDevelop_3.0.2