我想在 xamarin android 项目中运行以下委托。
但是在运行之后,State类的对象S
包含null
。
此错误指向代码中的以下行。
tv.Text = s.name+""+s.population;
tv
在我的代码中是textview
。
button.Click += async delegate {
state s = new state();
HttpClient _client = new HttpClient();
string url = "http://iforindia.azurewebsites.net/api/state/uid/33F8A8D5-0DF2-47A0-9C79-002351A95F88";
HttpResponseMessage response = await _client.GetAsync(url);
if (response.ReasonPhrase.Contains("OK"))
{
if (response != null)
{
var jsonSerializer = new DataContractJsonSerializer(typeof(state));
var stream = await response.Content.ReadAsStreamAsync();
s= (state)jsonSerializer.ReadObject(stream);
}
}
else if (response.ReasonPhrase.Contains("Bad Request"))
{
s= null;
}
else
{
s= null;
}
tv.Text = s.name+""+s.population;
};
答案 0 :(得分:2)
这是多余的(response.ReasonPhase已经引发了一个空异常):
if (response != null)
试试这个:
button.Click += async delegate {
var client = new HttpClient();
var url = "http://iforindia.azurewebsites.net/api/state/uid/33F8A8D5-0DF2-47A0-9C79-002351A95F88";
var response = await _client.GetAsync(url);
if (response != null && response.ReasonPhrase.Contains("OK"))
{
var jsonSerializer = new DataContractJsonSerializer(typeof(state));
var stream = await response.Content.ReadAsStreamAsync();
var s = jsonSerializer.ReadObject(stream) as state;
if (s != null)
{
tv.Text = s.name+""+s.population;
}
}
};