Search code examples
c#xamarin.formsdotnet-httpclient

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;

Solution

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