在我以前的文章中,我问过有关使用C#正文从Http Get Request获取数据的问题。现在我面临另一个错误,int(root.frame(),16) # root is a Tk() or Toplevel()
有人知道如何解决此问题吗?
代码
Android.Util.AndroidRuntimeException: 'Only the original thread that created a view hierarchy can touch its views.'
答案 0 :(得分:0)
尝试以下类似操作(假设整件事是一个名为“ SomeFunction
”的函数)
private void SomeFunction() {
Device.BeginInvokeOnMainThread(() => {
var client = new HttpClient();
var request = new HttpRequestMessage {
Method = HttpMethod.Get,
RequestUri = new Uri("my url"),
Content = new StringContent("my json body content", Encoding.UTF8, "application/json"),
};
var response = await client.SendAsync(request).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
var responsebody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
string text = responsebody.ToString();
string[] str = text.Split(new [] {
',',
':'
}, StringSplitOptions.RemoveEmptyEntries);
string result = str[10];
labelTxt.Text = result;
});
}
答案 1 :(得分:0)
嗨,请尝试以下代码。
public async static Task<T> GetResultAsync<T>(string Url)
{
try
{
if (CrossConnectivity.Current.IsConnected)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(BaseUrl);
client.DefaultRequestHeaders.Clear();
client.SetBearerToken(Helpers.Settings.ServiceToken);
client.DefaultRequestHeaders.Add("Language", Helpers.Settings.AppLanuageSetting);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync($"{Url}").ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(result,new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.None });
}
else
{
return default(T);
}
}
}
else
{
Acr.UserDialogs.UserDialogs.Instance.Toast("Please check your internet connection");
return default(T);
}
}
catch (Exception Ex)
{
Logging.ErrorLog(Ex, "GetResultAsync");
return default(T);
}
}
并使用此方法
var结果=等待APIService.GetResultAsync>($“ {ApiEndpoints} / {” Paramters1“} / {pageNo}”);
答案 2 :(得分:0)
如上面curiousBoy所说,您只能从UI线程(主线程)修改UI元素。
因此您可以尝试将<Button
title="Add User"
onPress={() => this.props.navigation.navigate('AddNewUser')}
/>
放在labelTxt.Text = result;
方法中。
Device.BeginInvokeOnMainThread