tags:

views:

30

answers:

2

I am an android beginner.

I'm struggling to understand why startActivity runs properly when copied from a tutorial I found and fails when I make the smallest change.

Code from the tutorial:

private class ButtonHandler implements View.OnClickListener {
    public void onClick(View v) {
        handleButtonClick();
    }   
}

private void handleButtonClick() {
    startActivity(new Intent(this, SecondAct.class));
}

That works. When I try to change it to what I would consider a simpler design, I am getting an error.

private class ButtonHandler implements View.OnClickListener {
    public void onClick(View v) {
        startActivity(new Intent(this, SecondAct.class));
    }   
}

The error is:
The constructor Intent(FirstTwoApps.ButtonHandler, Class) is undefined

Notice that all I did was moved the action from the handleButtonClick() method to the onClick() method. Apparently that is not allowed, but I don't understand why.

Any help is greatly appreciated.

+2  A: 

You need to change your this reference to that of the enclosing class, i.e. if your class is named Main, change it to Main.this.

JRL
Yeah, I didn't even know you could do that in Java until I started working with Android. +1
iandisme
Thank you very much. This fixed it.
alockrem
+1  A: 

Because startActivity is a method of Context. In the first example, it is being run from a Context object, in the second it is being run from a ButtonHandler object. This is a scoping problem.

fredley
Thank you very much. This helps me understand why the error is happening, which will help me troubleshoot similar issues in the future.
alockrem