user1367903
user1367903

Reputation: 1

Error with setOnClickListener(this)

I have used the code that Eclipse creates by default and added a button with an OnClickListener.

The following code crashes at the last line where I use setOnClickListener(this).

public class MainActivity extends Activity implements OnClickListener {

    private Button startStopButton;

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

        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }

        startStopButton = (Button) findViewById(R.id.startButton);
        startStopButton.setOnClickListener(this);
    }

This is probably something trivial but I don't understand what the issue is. The onClick method is defined below if that is in any way relevant, but it does nothing right now.

Using onClick in the layout xml works, but I have read elsewhere that it is bad practice to use it.

Thanks in advance !

Upvotes: 0

Views: 243

Answers (4)

Isuru
Isuru

Reputation: 161

Please implement the onclick() method.

public void onClick(View v){
        if(v.getId()==R.id.startButton)
{
    //type what you want to do here
}
}

Upvotes: 0

Jorgesys
Jorgesys

Reputation: 126533

The problem is that you are loading a fragment

 if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }

and into the PlaceholderFragment() doesn´t exist a reference of startButton

 startStopButton = (Button) findViewById(R.id.startButton);

your problem is similar to this post:

Unable to load url in webview (android)

Upvotes: 1

user1223530
user1223530

Reputation:

Replace startStopButton.setOnClickListener(this);
with

startStopButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent i=new Intent("com.monster.android.activitylifecycle.SecndActivity");
                startActivity(i);

            }
        });

You are passing this which is refering to object of current activity..instead you should pass object of annonymouse class View.OnClickListener which implements onclick() method..

Upvotes: 0

Helmisek
Helmisek

Reputation: 1319

Try changing the line implements OnClickListener to implements View.OnClickListener :-) Or as I see now. Are you sure that the button is not in the XML layout file, which belongs to PlaceHolderFragment?

Upvotes: 0

Related Questions