0

This is my starting activity. I'm trying to get this button to work but it's been giving me this error.

Line 15 button can not be resolved.

    package com.synamegames.giveaway;

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

public class GiveawayActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Button register = (Button) findViewById(R.id.register);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // Perform action on clicks

            }
        });
        setContentView(R.layout.main);
    }
}
0

3 Answers 3

4

Please try this..

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final Button register = (Button) findViewById(R.id.register);
        register.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on clicks

            }
        });

    }
4
  • This is the correct answer. findViewById() can only be called after setContentView(). Otherwise, android doesn't know which layout file to look in for R.id.register
    – theisenp
    Jul 7, 2011 at 13:03
  • Nope, it still says button can not be resolved. Is it because i need to create an OnClickListener class? Or does my importing of the view.view.onclicklistener void that?
    – Drake
    Jul 7, 2011 at 13:05
  • @drake check my answer and if find this is right then upvote and right this answer so more help to other also..
    – Nikhil
    Jul 7, 2011 at 13:16
  • @drake Did you make sure to replace button.setOnClickListener with register.setOnClickListener?
    – thegrinner
    Jul 7, 2011 at 19:24
1

The problem is You have defined the Button instances as register in the line final Button register = (Button) findViewById(R.id.register); But you are setting onclick listener to the button instance which is not defined. You should have

register.setOnClickListener(new OnClickListener() {

instead of

button.setOnClickListener(new OnClickListener() {
1

U can use android:onClick from xml and pass a the view into the .java file eg:

android:onClick="bactToList" 

in java:

   public void bactToList(View view){

   } 

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.