Trey Balut
Trey Balut

Reputation: 1395

Android ListView Error with Xamarin

I'm getting an Unhandled Exception error: "System.NullReferenceException: Object reference not set to an instance of an object" when trying to run the following Xamarin Android app.

using Android.App;
using Android.OS;
using Android.Widget;
using System;

namespace CrossTest1.Droid
{
    [Activity(Label = "CrossTest1.Droid", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : ListActivity
    {
        private int count = 1;

        private BetsViewModel viewModel1;

        private String[] planets = new String[] { "Apple", "Banana", "Mango", "Grapes" };

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            viewModel1 = new BetsViewModel();

            Button button = FindViewById<Button>(Resource.Id.myButton);

            ArrayAdapter adapter = new ArrayAdapter<String>(this, Resource.Id.listView1, Resource.Id.label, planets);

            ListView listView = (ListView)FindViewById(Resource.Id.listView1);
            listView.SetAdapter(adapter);

            button.Click += delegate
           {
               button.Enabled = false;

               button.Enabled = true;
           };
        }
    }
}

Below is my axml file.

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <Button
        android:id="@+id/myButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
    <ListView
        android:minWidth="25px"
        android:minHeight="25px"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listView1" />
   <TextView 
      android:id="@+id/label"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:padding="10dip"
      android:textSize="16dip"
      android:textStyle="bold" />

</LinearLayout>

Upvotes: 0

Views: 1059

Answers (1)

SushiHangover
SushiHangover

Reputation: 74209

I would assume you are getting an Android inflater exception at runtime on this:

ArrayAdapter adapter = new ArrayAdapter<String>(this, Resource.Id.listView1, Resource.Id.label, planets);

You need pass your item's layout instead of the Listview:

ArrayAdapter adapter = new ArrayAdapter<String>(this, Resource.Id.YOURLISTVIEWITEMLAYOUT, Resource.Id.label, planets);

Upvotes: 1

Related Questions