成功构建和安装apk后,Android Studio App在运行时崩溃

时间:2018-02-11 13:41:30

标签: android android-studio

这是我在登录屏幕上使用的简单java代码。在我应用的启动画面后,应用程序自动关闭。它没有进一步。该怎么办?

public class MainActivity extends AppCompatActivity {
EditText username = (EditText)findViewById(R.id.input_email);
EditText password = (EditText)findViewById(R.id.input_password);
Button loginButton = (Button) findViewById(R.id.btn_login);
int counter=3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); }

//Login Button Code

public void onBtn(View v){
if(username.getText().toString().equals("shubham.goyal1210@gmail.com")&&
(password.getText().toString().equals("shubham")))
{
Toast.makeText(this, "Login Success", Toast.LENGTH_LONG).show();}
else {
Toast.makeText(this, "Login Failed", Toast.LENGTH_SHORT).show();
counter--;
if(counter==0){ loginButton.setEnabled(false); }
else 
{ 
Toast.makeText(this, counter+" attempts left", Toast.LENGTH_SHORT).show(); }
}}

//Sign Up Button Code

public void linkSign(View v){
Intent intent = new Intent(this, signupActivity.class);
startActivity(intent);
}}

2 个答案:

答案 0 :(得分:2)

移动

EditText username = (EditText)findViewById(R.id.input_email);
EditText password = (EditText)findViewById(R.id.input_password);
Button loginButton = (Button) findViewById(R.id.btn_login);
setContentView之后

将参考变量保留在oncreate之外,因为在调用setContentView后,视图仅在活动的UI层次结构中可用

EditText username;
EditText password;
Button loginButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main); 
    username = (EditText)findViewById(R.id.input_email);
    password = (EditText)findViewById(R.id.input_password);
    loginButton = (Button) findViewById(R.id.btn_login);
}

答案 1 :(得分:0)

您在错误的地方初始化EditTextButton视图,您需要在onCreate方法中对其进行初始化,如下所示。

public class MyActivity extends AppCompatActivity {


    EditText username;

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

        username = (EditText)findViewById(R.id.input_email);
       ...

    }


}