我有一个奇怪的问题。我是编码应用程序,它使用来自Web的XML。在模拟器上它很好,但在手机上它崩溃(点击按钮后关闭,没有任何警报)。
以下是代码:
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Xml;
namespace KursyWalut
{
[Activity (Label = "KursyWalut", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Popularne);
// Get our button from the layout resource,
// and attach an event to it
Button button = FindViewById<Button> (Resource.Id.przycisk);
TextView data = FindViewById<TextView> (Resource.Id.data);
TextView kurs = FindViewById<TextView> (Resource.Id.kurs);
RadioGroup radioGroup = FindViewById<RadioGroup> (Resource.Id.radioGroup);
RadioButton dolar = FindViewById <RadioButton> (Resource.Id.rbDolar);
RadioButton euro = FindViewById <RadioButton> (Resource.Id.rbEuro);
RadioButton frank = FindViewById <RadioButton> (Resource.Id.rbFrank);
int checkedRadioButton;
XmlDocument dokument = new XmlDocument ();
// --------------------------------------------------------------------------
button.Click += delegate {
try{
dokument.Load("http://nbp.pl/kursy/xml/LastA.xml");
}
catch(Exception ex){
Toast.MakeText(this,"Brak połaczenia z Internetem!",ToastLength.Long);
}
data.Text = "Data: " + getDocumentDate(dokument);
checkedRadioButton = radioGroup.CheckedRadioButtonId;
switch(checkedRadioButton){
case Resource.Id.rbDolar:
kurs.Text = "Kurs USD: " + getRate(dokument,"USD");
break;
case Resource.Id.rbEuro:
kurs.Text = "Kurs EUR: " + getRate(dokument,"EUR");
break;
case Resource.Id.rbFrank:
kurs.Text = "Kurs CHF: " + getRate(dokument,"CHF");
break;
}
};
}
String getDocumentDate(XmlDocument xml){
return xml.SelectSingleNode("/tabela_kursow/data_publikacji").InnerText;
}
String getRate(XmlDocument xml, String currency){
foreach (XmlNode xmlNode in xml.DocumentElement) {
if (xmlNode.Name == "pozycja") {
if (xmlNode.SelectSingleNode ("kod_waluty").InnerText == currency)
return xmlNode.SelectSingleNode ("kurs_sredni").InnerText;
}
}
return "Nie znaleziono kursu";
}
}
}
答案 0 :(得分:1)
好吧,我想我找到了。您当前正在阅读按钮中的文档。点击。您应该尝试在后台线程中执行此操作。以任务并行库为例:
XmlDocument dokument = new XmlDocument ();
Task task = Task.Factory.StartNew(() =>
{
try
{
dokument.Load("http://nbp.pl/kursy/xml/LastA.xml");
}
catch (Exception ex)
{
Toast.MakeText(this, "Brak połaczenia z Internetem!", ToastLength.Long);
}
});
答案 1 :(得分:0)
首先,如果dokument.Load()
中存在异常,它将通过catch处理程序进入,即使文档未加载,您的代码也会继续运行。您应该将捕获处理程序更改为:
try
{
// read xml into string
var xml = new System.Net.WebClient()
.DownloadString("http://nbp.pl/kursy/xml/LastA.xml");
dokument.LoadXml(xml);
}
catch (Exception ex)
{
Toast
.MakeText(this, "Brak połaczenia z Internetem! " + ex, ToastLength.Long)
.Show();
return;
}
注意我在.Show()
末尾添加了MakeText()
。否则,你不会看到实际的Toast。我还添加了实际的异常。
我感觉您在加载文档时遇到异常。一旦确定原因,其余部分应该更容易理解。