Question

I want to put an imageview on the screen but. It gave "object reference null" exception. I think that I have a logical error. please help me to find it.

Here is my code :

My layout xml :

    <?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/button"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/changeImage"/>  
    <ImageView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/sampleviewer"
    android:src="@drawable/sampleimage"        
    android:scaleType="fitCenter"/>   

    </LinearLayout>         

In OnCreate Function :

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

        //Create the user interface in code
        var layout = new LinearLayout (this);
        layout.Orientation = Orientation.Vertical;

        var aLabel = new TextView (this);
        aLabel.Text = "Hello, Xamarin.Android";

        var aButton = new Button (this);      
        aButton.Text = "Say Hello";
        aButton.Click += (sender, e) => {
            aLabel.Text = "Hello from the button";
        };  

        var button = new Button (this);
        button.Text = "AAAAAA";


        button.Click += delegate {

            aLabel.Text = " PRESS THE BUTTON";
            var imageView = FindViewById<ImageView> (Resource.Id.sampleviewer); // After this line imageView variable is still null
            imageView.SetImageResource (Resource.Drawable.sampleimage);
        };

        layout.AddView (aLabel);
        layout.AddView (aButton);           
        layout.AddView (button);
        SetContentView (layout);


   }
Was it helpful?

Solution

You're building your layout in two different ways here.

  1. You have an XML layout containing your ImageView, but you never reference that XML layout anywhere in code, so Android never loads it (and therefore you can't access it).
  2. You also create a layout in Java code by creating a new LinearLayout object and adding other views to it. This layout has no ImageView.

When you call SetContentView() here:

SetContentView (layout);

You're telling Android to use the layout you created in code. If you want to use the XML layout, you can change to:

SetContentView(Resource.Layout.Main);

(Replacing Main with the actual name of your XML file.)

Otherwise, you'd need to add the ImageView in your Java code. But you probably don't want to mix and match XML layouts with Java code layouts.

Also note that you must call SetContentView() before calling FindViewById().

You might also want to read through Xamarin's Resource Layouts tutorial.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top