Android - Nullpointerexception Error

Asked

Viewed 65 times

0

I’m getting the following error randomly, IE, gives error sometimes and sometimes not:

Caused by: java.lang.NullPointerException
            at pt.cartuxa.Login.onCreate(Login.java:62)

My line 62 is as follows::

password.setImeActionLabel(getString(R.string.keyboard_enter), KeyEvent.KEYCODE_ENTER);

Complete code:

public class Login  extends Activity {

    EditText username, password;
    Editable user_input, pass_input;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // SETTERS
        username = (EditText) findViewById(R.id.txt_login_user);
        password = (EditText) findViewById(R.id.txt_login_pass);

        // VIEW
        setContentView(R.layout.login_layout);

        // VIEW CONFIGS
        password.setImeActionLabel(getString(R.string.keyboard_enter), KeyEvent.KEYCODE_ENTER);

    }
}

I created line 62 to change the text of the Enter button to "Login" but it turns out that when I run the application, it sometimes initializes correctly and sometimes blocks this line giving the error described above.

How can I avoid that mistake?

1 answer

4


The problem is you’re looking for the View's of its layout before adding its own to the Activity, using the method setContentView. When you do that, he won’t find the View's that is asking in the findViewById, generating the NullPointerException.

Call the setContentView before any manipulation of View, after the super.onCreate() of course.

Your code should be:

public class Login  extends Activity {

    EditText username, password;
    Editable user_input, pass_input;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Adicione o layout antes de qualquer manipulacao relativa ao mesmo
        // VIEW
        setContentView(R.layout.login_layout);

        // SETTERS
        username = (EditText) findViewById(R.id.txt_login_user);
        password = (EditText) findViewById(R.id.txt_login_pass);

        // Restante do seu código
    }
}
  • Thank you very much, that was exactly the problem

Browser other questions tagged

You are not signed in. Login or sign up in order to post.