Question

I'm wondering what's wrong with my Android Development Tools. I can add a Button or ImageButton on layout, but later in my code I just can't add

myButton.setOnClickListener(new OnClickListener) { ...

I've tried to test the buttons on my device but I got an exeption and my program terminates. And it doesn't matter if I add my own ImageButton or if I use predefined ADT buttons with default settings.

Any help is welcome!

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<ImageButton
    android:id="@+id/imageButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/btn_unlocked" />

</LinearLayout>

MainActivity.java:

public class MainActivity extends Activity { 

ImageButton lock1;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    lock1 = (ImageButton) findViewById(R.drawable.btn_unlocked);

    lock1.setOnClickListener(new View.OnClickListener() {   
        @Override
        public void onClick(View v) {
            finish();
        }
    }); 
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
}
Was it helpful?

Solution

You are trying to put a Drawable in your ImageButton variable. That's not the correct way as you might have already guessed by the name of the method: findViewBy**Id**().

You'll need to pass Android the ID of your view so that it is able to retrieve it from the xml (Well, not from the xml, but you get the point). Altough you didn't post the logcat error output I would assume that your program died with a NullPointerException

That is because if findViewById() does not find a View for the given id it will return null as you can read here. Your program will then die at the .setOnClickListener() line because you invoke a method call on a null object.

So to make a long story short: Edit this line:

lock1 = (ImageButton) findViewById(R.drawable.btn_unlocked);

to look like this:

lock1 = (ImageButton) findViewById(R.id.imageButton1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top