Search code examples
androidlogin-script

My android login app unfortunately stopped


My simple app getting unfortunately stopped error.
Kindly solve, please.

I do not need any permissions

Here is my android main activity:

package vk.com.login_simple;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.*;


public class MainActivity extends AppCompatActivity {
private EditText username=(EditText) findViewById(R.id.username);
private EditText password=(EditText) findViewById(R.id.password);
private Button login=(Button) findViewById(R.id.login);
private Button reset=(Button) findViewById(R.id.reset);
private Button exit=(Button) findViewById(R.id.exit);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("Login App");
        setContentView(R.layout.activity_main);

    }
    public void login(View view){
if(username.getText().toString().equals("admin")&&password.getText().toString().equals("password")){
    Toast.makeText(getApplicationContext(),"Login Success",Toast.LENGTH_LONG).show();
//your code here
}else{
    Toast.makeText(getApplicationContext(),"Wrong Username / Password",Toast.LENGTH_LONG).show();
}
    }

    public void reset(View view) {
        username.setText("");
        password.setText("");
        Toast.makeText(this,"Reset success",Toast.LENGTH_LONG).show();
    }
    public void exit(){
        //empty
    }
}

Solution

  • findViewById ONLY work after you setContentView() which define the root view of your layout, to show where the Views can be found. If you call it outside Android don't know how and where to find Views for you.

    So what you MUST do is place all of the findViewById() code inside onCreate() and after setContentView().

    private EditText username;
    private EditText password;
    private Button login;
    private Button reset;
    private Button exit;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            setTitle("Login App");
    
            username=(EditText) findViewById(R.id.username);
            password=(EditText) findViewById(R.id.password);
            login=(Button) findViewById(R.id.login);
            reset=(Button) findViewById(R.id.reset);
            exit=(Button) findViewById(R.id.exit);
    
        }