Home » Android » listview – System.NullReferenceException Xamarin Android-Exceptionshub

listview – System.NullReferenceException Xamarin Android-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I want that field ArrayAdapter what i initialize in Mainactivity, and set it up in OnCreate can be seen for method UpdateAdapter, for now i have error like this: System.NullReferenceException Object Reference not set to an instance of object:
image of error
public class MainActivity : AppCompatActivity
{
ListView mainlist;
List lista = new List();
public ArrayAdapter 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;}}...

    public void UpdateAdapter(BluetoothDevice device )
    {
        lista.Add(device.Name);
        arrayAdapter.NotifyDataSetChanged();
    }
How to&Answers:

For an ArrayAdapter, notifyDataSetChanged only works if you use the add(), insert(), remove(), and clear() on the Adapter.

try to change :

lista.Add(device.Name);
arrayAdapter.NotifyDataSetChanged();

to

arrayAdapter.Add(device.Name);
arrayAdapter.NotifyDataSetChanged();