Alex1McGrady
Alex1McGrady

Reputation: 135

App crashes when I press the button on phone

I'm totally new to this and it's my first app that I'm building. The problem is that when I press the button from my first activity in order to go to the second one the app crashes.

Here is the activity code:

private TextInputLayout password;
private View login;


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

    Button login = (Button)findViewById(R.id.btn_login);
    login.setOnClickListener(new View.OnClickListener(){
        @Override
        public  void onClick(View v){
            if (password.getEditText().getText().toString().equals("alex")) {
                finish();
                startActivity(new Intent(LoginActivity.this,MainActivity.class));
            } else {
                Toast.makeText(LoginActivity.this, "Wrong Input", Toast.LENGTH_SHORT).show();
            }
        }
    });

}

Upvotes: 1

Views: 39

Answers (1)

AnasAbubacker
AnasAbubacker

Reputation: 3607

You should have statement like this

password =(TextInputLayout)findViewById(R.id.your_id); 

As I believe it is because password is not initialised. (You will get Null pointer exception)

You can modify your on create method like this

private EditText password; private Button login;

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

    password =(TextInputLayout)findViewById(R.id.password); 
        login =(Button)findViewById(R.id.btn_login);
        login.setOnClickListener(new View.OnClickListener(){
            @Override
            public  void onClick(View v){
                if (password.getEditText().getText().toString().equals("alex"))
                {

                startActivity(new Intent(LoginActivity.this,MainActivity.class));
                 finish();
                } else {
                    Toast.makeText(LoginActivity.this, "Wrong Input", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

And don't forget to have an entry in manifest.xml file for MainActivity.class

Upvotes: 1

Related Questions