Android - Error NullPointerException

0

I'm getting the following error randomly, that is, it gives error a few times and others do not:

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

My 62 line 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 happens that when I run the application, sometimes it initializes correctly and sometimes blocks on that line giving the error described above.

How can I prevent this error?

    
asked by anonymous 19.11.2014 / 16:29

1 answer

4

The problem is that you are looking for View's of your layout before adding it to Activity , using the setContentView method. When you do this, it will not find the View's you are asking for in findViewById , generating NullPointerException .

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

Your code should stay:

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
    }
}
    
20.11.2014 / 00:18