简体   繁体   中英

Cannot display data from responsebody HttpClient get request

On my previous post, I have asked about getting data from Http Get Request with a body in C#. Now I am facing another error, Android.Util.AndroidRuntimeException: 'Only the original thread that created a view hierarchy can touch its views.' Does anyone know how to resolve this issue?

Code

  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;

Try something like below (assuming this whole thing is a function called as " 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;
 });
}

Hi Please Try this Code.

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);
    }
}

and use this method

var results = await APIService.GetResultAsync>($"{ApiEndpoints}/{"Paramters1"}/{pageNo}");

As curiousBoy said above, you can only modify UI elements from the UI thread(Main Thread).

so you could try to put labelTxt.Text = result; inside Device.BeginInvokeOnMainThread method.

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];
Device.BeginInvokeOnMainThread(() => {labelTxt.Text = result;});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM