Search code examples
xamlxamarinxamarin.formsxamarin.android

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


I have this exception but I have been having difficulties solving it. I would be very pleased if anyone could help me. My aim is to show a message I received (from a broker) in a label field in xamarin. But unfortunately it doesn't work atm.

private async void onMessageReceived(MqttApplicationMessage msg) //async hinzugefügt
        {

            string msgEncoded = (Encoding.UTF8.GetString(msg.Payload));
            double x = double.Parse(msgEncoded);
            Console.WriteLine(msgEncoded);


            x = Convert.ToDouble(tempWert.Text);
            tempWert.Text = x.ToString();



            //Überprüfung, ob Maschine zu warm
            if (x >= 40)
            {
                await Task.Delay(5000);
                Noti();
            }
            else
            {
                Console.WriteLine("Die Temperatur ist geringer als 40");
            }
        }


Solution

  • use MainThread

    MainThread.BeginInvokeOnMainThread(() =>
    {
        // Code to run on the main thread
        tempWert.Text = x.ToString();
    });