4

When I press any button I get:

System.NullReferenceException: Object reference not set to an instance of an object.

MainActivity.cs

namespace Xamarin.Android.Pluralsight
{
    [Activity(Label = "Xamarin.Android.Pluralsight", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        private Button _buttonPrevious;
        private Button _buttonNext;
        private ImageView _imageProfile;


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

        SetContentView(Resource.Layout.Main);

        _buttonPrevious = FindViewById<Button>(Resource.Id.buttonPrevious);
        _buttonNext = FindViewById<Button>(Resource.Id.buttonNext);
        _imageProfile = FindViewById<ImageView>(Resource.Id.imageProfile);

        _buttonNext.Click += buttonNext_Click;
        _buttonPrevious.Click += buttonPrevious_Click;
    }

    private void buttonPrevious_Click(object sender, EventArgs e)
    {
        _imageProfile.SetImageResource(Resource.Drawable.image1);
    }

    private void buttonNext_Click(object sender, EventArgs e)
    {
        _imageProfile.SetImageResource(Resource.Drawable.image2);
    }
}

}

Main.axml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
  <Button
      android:id="@+id/buttonPrevious"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Previous"
      android:layout_alignParentBottom="true"
      android:layout_alignParentLeft="true" />
  <Button
      android:id="@+id/buttonNext"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Next"
      android:layout_alignParentBottom="true"
      android:layout_alignParentRight="true" />
  <ImageView
      android:id="@+id/imageProfile"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:src="@drawable/image1" />
</RelativeLayout>

Why? What's wrong with this code? This code is rudimentary, but I cannot solve the problem.

1 Answer 1

5

There's nothing wrong with your code.

At runtime, Android can't find your imageProfile view, soFindViewById<ImageView>(Resource.Id.imageProfile) is returning null.

Try deleting the contents (not the file) of Resource.designer.cs and rebuilding.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your advice. It was very helpful. It works for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.