Rhuarc13
Rhuarc13

Reputation: 135

ImageButton is 'null' after assignment

This is my first time creating an Android app, and I'm not sure how to fix this issue. I'm trying to point an ImageButton variable to an existing ImageButton by ID, but I keep getting a NullPointerException. Here's the code:

    ...
    import android.widget.ImageButton;

    public class StartActivity extends ActionBarActivity {
        ImageButton addButton;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);
                addButton = (ImageButton) findViewById(R.id.add_category_button);
        }...

The ImageButton is located in the layout card_categories. Here's the XML for that layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/main_page"
android:weightSum="1">


    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/add_category_button"
        android:layout_gravity="right"
        android:background="@drawable/add_button"
        android:width="50dp"
        android:height="50dp"
    />
</LinearLayout>

I'm not sure if the issue is an improper id, or what, but it's not pulling the ImageButton in the XML correctly. Thanks for your help!

Update: I tried assigning the ImageButton after setContentView(R.layout.card_categories) , but it still is null.

OnClickListener myCardsHandler = new OnClickListener() {
    public void onClick(View v) {
        setContentView(R.layout.card_categories);
        addButton = (ImageButton) findViewById(R.id.add_category_button);
        loadCategories(dbHandler, categories);
    }
};

Upvotes: 0

Views: 57

Answers (2)

throws_exceptions_at_you
throws_exceptions_at_you

Reputation: 1746

Try this

@Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.card_categories);
       addButton = (ImageButton) findViewById(R.id.add_category_button);
       addButton.setOnClickListener(myCardsHandler);
   }

   OnClickListener myCardsHandler = new OnClickListener() {
       public void onClick(View v) {

           loadCategories(dbHandler, categories);
       }
   };

Upvotes: 1

Michał Szydłowski
Michał Szydłowski

Reputation: 3419

You're setting the wrong layout in your setContentView method. So it's not surprising, that the compiler will not find any ImageButton of that name there.

Either inflate card_categories:

setContentView(R.layout.activity_start);

or place your ImageButton in the layout you have currently set.

Upvotes: 0

Related Questions