1

I keep getting this java.lang.NullPointerException on the line where mLoginButton's onClickListener is initiated.

I don't know what is wrong and have tried cleaning and rebuilding the project but it doesn't work.

Here's the relevant code:

public class LoginActivity extends Activity {
/** Called when the activity is first created. */
private Button mLoginButton;
private Button mNewAccountButton;

@Override
public void onCreate(Bundle savedInstanceState) {

    mLoginButton = (Button) findViewById(R.id.login_button);
    mNewAccountButton = (Button) findViewById(R.id.newaccount_button);

    super.onCreate(savedInstanceState);

    setContentView(R.layout.login);

    registerButtonListenersAndSetDefaultText();
}

private void registerButtonListenersAndSetDefaultText() {
    mLoginButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showToast(getString(R.string.login_message));
            finish();
        }
    });
    mNewAccountButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showToast(getString(R.string.newacount_message));
            finish();
        }
    });
}

private void showToast(String toastString) {
    //do something       
}
}

thanks!

1
  • Which line inside the onClickListener initialization is it happening? Commented Mar 22, 2012 at 22:08

1 Answer 1

9

You are trying to findViewById before you setContentView. You must set the content view before you reference any view objects.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.