Namone
Namone

Reputation: 121

setOnClickListener Error: No Idea Why?

I am new to Android Development, and I can't for the life of me, figure out why this is giving me an error. The error is occurring on this line: 'bu.setOnClickListener(new OnClickListener() {'

I am following the Android Development Fundamental tutorials on Lynda.com; and my code is identical to that of the teachers; or so I think.

package com.lynda.lyndaproject;

import android.os.Bundle;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class Main extends Activity {

    Button bu = (Button) findViewById(R.id.button1);

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

        bu.setOnClickListener(new OnClickListener() {
            public void onClick(View v){
            }               
        });
    }   
}

By the way, Eclipse doesn't seem to be allowing me to import anything; and I do believe importing 'android.view.View' should have imported everything necessary.

Upvotes: 0

Views: 1792

Answers (1)

Phil
Phil

Reputation: 36289

First, you need to fix your import. You are using the wrong OnClickListener. Change the line

import android.content.DialogInterface.OnClickListener;

to

import android.view.View.OnClickListener;

Next, You need to move the line

Button bu = (Button) findViewById(R.id.button1);

To after the call to setContentView(...). So your onCreate method would look like:

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

    Button bu = (Button) findViewById(R.id.button1);

    bu.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v){

        }


    });
}

This is because findViewById(...) looks for a View in the current layout. Since this has not been set by setContentView, it will always return null.

Upvotes: 4

Related Questions