更改标签文本时“对象引用未设置为对象的实例”

时间:2019-11-11 16:09:05

标签: c# android xamarin xamarin.forms mono

每次尝试检测到新的心跳时我都试图更新标签(目前仅是一个计数器)。为此,我创建了自己的事件处理程序。该处理之所以有效,是因为如果我注释掉 HeartRate.Text =“ Test”; ,则调试仅显示:

[0:] Heart rate is changed
[0:] The heartrate is now: 822.00
[0:] Heart rate is changed
[0:] The heartrate is now: 823.00
[0:] Heart rate is changed
[0:] The heartrate is now: 824.00

这是我的代码:

using Plugin.BLE;
using Plugin.BLE.Abstractions.Contracts;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace BAP_App
{
    public class HeartRateDataPage : ContentPage
    {
        public HeartRateDataPage()
        {
            var adapter = CrossBluetoothLE.Current.Adapter;                     //gets the bluetooth adapter
            Title = "HeartRateDataPage";

            Label title = new Label()
            {
                Text = "Heart Rate",
                FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label)),
                VerticalOptions = LayoutOptions.CenterAndExpand,
                HorizontalOptions = LayoutOptions.Center
            };

            Label HeartRate = new Label()
            {
                Text = "0",
                VerticalOptions = LayoutOptions.CenterAndExpand,
                HorizontalOptions = LayoutOptions.Center,
                FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label))
            };

            Button Update = new Button()
            {
                Text = "Update"
            };

            Update.Clicked += (object sender, EventArgs e) =>
            {
                GetHeartRate(adapter);
            };

            HeartRateMonitor.HeartRateChanged += (o, args) =>
            {
                ShowHeartRateChange();
                HeartRate.Text = "Test";
            };

            Content = new StackLayout
            {
                Children =
                {
                    title,
                    HeartRate,
                    Update
                }
            };
        }

        private async void GetHeartRate(IAdapter adapter)
        {
            string serviceguid = "00001809-0000-1000-8000-00805f9b34fb";
            string characteristicguid = "00002a4e-0000-1000-8000-00805f9b34fb";

            Debug.WriteLine("Starting to get HearRateValue!");
            IService service = await BLE.SearchService(adapter,serviceguid);
            Debug.WriteLine("The service I found is: " + service.Id.ToString());
            ICharacteristic characteristic = await BLE.SearchCharacteristic(service, characteristicguid);
            Debug.WriteLine("The characteristic I found is: " + characteristic.Id.ToString());
            BLE.UpdateValueStart(characteristic);
        }

        public void ShowHeartRateChange()
        {

            Debug.WriteLine("Heart rate is changed");
            Debug.WriteLine("The heartrate is now: " + System.Text.Encoding.ASCII.GetString(HeartRateMonitor.HeartRateValue));
        }
    }
}


但是当我尝试使用 HeartRate.Text =“ Test”; 更改标签时,会出现以下异常:

[0:] Heart rate is changed
[0:] The heartrate is now: 969.00
Object reference not set to an instance of an object.
System.NullReferenceException: Object reference not set to an instance of an object.
   at Mono.Debugging.VisualStudio.ExceptionsAdapter.OnUnhandledException(Object sender, TargetEventArgs args) in E:\A\_work\2239\s\src\Debugging.VisualStudio.Vsix\Integration\ExceptionsAdapter.cs:line 71
   at Mono.Debugging.Client.DebuggerSession.OnTargetEvent(TargetEventArgs args) in E:\A\_work\2239\s\external\debugger-libs\Mono.Debugging\Mono.Debugging.Client\DebuggerSession.cs:line 1143
   at Mono.Debugging.Soft.SoftDebuggerSession.HandleBreakEventSet(Event[] es, Boolean dequeuing) in E:\A\_work\2239\s\external\debugger-libs\Mono.Debugging.Soft\SoftDebuggerSession.cs:line 1906
   at Mono.Debugging.Soft.SoftDebuggerSession.HandleEventSet(EventSet es) in E:\A\_work\2239\s\external\debugger-libs\Mono.Debugging.Soft\SoftDebuggerSession.cs:line 1589
   at Mono.Debugging.Soft.SoftDebuggerSession.EventHandler() in E:\A\_work\2239\s\external\debugger-libs\Mono.Debugging.Soft\SoftDebuggerSession.cs:line 1489

文本标签保持不变,但有时会更改为“ T”。

FIX: 所以我收到此错误,因为标签的更改是异步完成的。对xamarin内部的UI所做的所有更改都需要在主线程上进行。然后,我将其调用到主线程上。

Device.BeginInvokeOnMainThread(() => HeartRate.Text = "Test");

0 个答案:

没有答案