System.NullReferenceException Xamarin Android arrayAdapter

System.NullReferenceException Xamarin Android arrayAdapter

通过 class MainActivity 初始化 ArrayAdapter,在 OnCreate 中设置它,并且仍在方法 UpdateAdapter(BluetoothDevice device) 中,我得到错误:System.NullReferenceException Object Reference not set to an instance of object

https://imgur.com/a/RFTK4NA

public class MainActivity : AppCompatActivity
    {
        ListView mainlist;
        List<string> lista = new List<string>();
        public ArrayAdapter<string> arrayAdapter; ...

        protected override void OnCreate(Bundle savedInstanceState)
        {
            mainlist = (ListView)FindViewById<ListView>(Resource.Id.listView1);
            arrayAdapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, lista);
            mainlist.Adapter = arrayAdapter;

...

        skanujbtn.Click += (sender, e) =>
        {
            var receiver_ = new BluetoothDeviceReceiver();
            IntentFilter filter = new IntentFilter(BluetoothDevice.ActionFound);
            RegisterReceiver(receiver_, filter);
            if (!bluetoothAdapter.IsDiscovering) bluetoothAdapter.StartDiscovery();}

        public void UpdateAdapter(BluetoothDevice device)
        {
            lista.Add(device.Name);
            arrayAdapter.NotifyDataSetChanged();
        }
    }

其他class

public class BluetoothDeviceReceiver : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        var action = intent.Action;
        if (action != BluetoothDevice.ActionFound)
        {
            return;
        }
    // Get the device
    var device = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);

    if (device.BondState != Bond.Bonded)
    {
        MainActivity obj = new MainActivity();
        obj.UpdateAdapter(device);

    }
}

代码讲的不多,你要分享一下你在哪里用的那个方法?

以下是我的猜测:

猜一:

问题:设备对象是在什么地方初始化的?

据我所知,您在方法中接收到的设备对象可能为空: 如果你有 class 这样的东西

public class BluetoothDevice
{
    public string Name { get; set; }
}

在传播到方法之前,您至少需要将其初始化为一个对象

 BluetoothDevice device = new BluetoothDevice()
 {
      Name = "SomeBluetoothDevice"
 };

猜测2:

您正在 Adapter 初始化之前调用 UpdateAdapter() 方法

编辑:

这是您从 Main 创建新实例的问题Activity

if (device.BondState != Bond.Bonded)
    {
        **MainActivity obj = new MainActivity();**
        obj.UpdateAdapter(device);

    }

这样它将创建一个新的 activity 实例,但它不会调用 OnCreate 方法,因为这不是创建活动的方式,您可以通过

类型的意图创建

无论如何,这是解决问题的方法: 使用 BluetoothDeviceReceiver 中 Activity 中已有的实例添加此代码:

public class BluetoothDeviceReceiver : BroadcastReceiver
    {
        MainActivity mainActivity;
        public BluetoothDeviceReceiver(MainActivity mainActivity)
        {
            this.mainActivity = mainActivity;
        }

        public override void OnReceive(Context context, Intent intent)
        {
            mainActivity.UpdateAdapter(device);
        }
    }

主要Activity:

 skanujbtn.Click += (sender, e) =>
 {
            var receiver_ = new BluetoothDeviceReceiver(this);
...
 }