Forum Xamarin Xamarin.Forms

HttpClient Get request with body Error C#

tohfutohfu Member ✭✭
edited April 9 in Xamarin.Forms

When I run my code, I have an error Android.Util.AndroidRuntimeException: 'Only the original thread that created a view hierarchy can touch its views.' .
Does anyone know how to solve this error? I can retrieve data with my code but I can't get it to display. I am trying to use Httpclient get request with a body to retrieve response and display in my application.

Code
` private async void EmployeeID()
{
var client = new HttpClient();

        var request = new HttpRequestMessage
        {
            Method = HttpMethod.Get,
            RequestUri = new Uri("url"),
            Content = new StringContent("body", 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[6];
        labelTxt.Text = result;
    }`

Best Answer

Answers

  • jezhjezh Member, Xamarin Team Xamurai

    Android.Util.AndroidRuntimeException: 'Only the original thread that created a view hierarchy can touch its views.

    It's fairly common practice that you can only modify UI elements from the UI thread.

    You can try to use following code:

        Device.BeginInvokeOnMainThread(() =>
                {
                  // wrap your code to modify  UI
    
                labelTxt.Text = result;
                });
    

    And in xamarin android, the equivalent code is:

         Activity.RunOnUiThread(() => {
    
                });
    

    Documentation for Activity.runOnUiThread

  • tohfutohfu Member ✭✭

    @jezh
    What do you mean wrap my code? I tried this set of code but I got the same error.

    `private void Button_Clicked(object sender, EventArgs e)
    {

            Device.BeginInvokeOnMainThread(async () =>
            {
                var client = new HttpClient();
    
                var request = new HttpRequestMessage
                {
                    Method = HttpMethod.Get,
                    RequestUri = new Uri("url"),
                    Content = new StringContent("json body"}", 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[6];
                labelTxt.Text = result;
            });
        }`
    
  • jezhjezh Member, Xamarin Team Xamurai

    @tohfu Hi friend, have you resolved your question?

  • tohfutohfu Member ✭✭

    @jezh Hi! Thanks a lot! I solved my problem :)

Sign In or Register to comment.