我正在处理需要注册活动的应用。我遇到的问题是每当我离开2个以上的EditTexts时我的应用程序崩溃了:这是我用于注册活动的代码:
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Register extends AppCompatActivity implements View.OnClickListener{
EditText etName, etAge, etUsername, etPassword;
Button bRegister;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
etName = (EditText) findViewById(R.id.etName);
etAge = (EditText) findViewById(R.id.etAge);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
bRegister = (Button) findViewById(R.id.bRegister);
bRegister.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bRegister:
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(Register.this);
String name = etName.getText().toString();
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
int age = Integer.parseInt(etAge.getText().toString());
if(!(name.trim().length()>0))
{
dialogBuilder.setMessage("Please enter your name");
dialogBuilder.setPositiveButton("Ok", null);
dialogBuilder.show();
break;
}
if(!(etAge.getText().toString().trim().length()>0) || age>120)
{
dialogBuilder.setMessage("Please enter your age");
dialogBuilder.setPositiveButton("Ok", null);
dialogBuilder.show();
break;
}
if(!(username.trim().length()>0))
{
dialogBuilder.setMessage("Please enter a username");
dialogBuilder.setPositiveButton("Ok", null);
dialogBuilder.show();
break;
}
if(!(password.trim().length()>0))
{
dialogBuilder.setMessage("Please enter a password");
dialogBuilder.setPositiveButton("Ok", null);
dialogBuilder.show();
break;
}
User user = new User(name, age, username, password);
registerUser(user);
break;
}
}
private void registerUser(User user) {
ServerRequests serverRequest = new ServerRequests(this);
serverRequest.storeUserDataInBackground(user, new GetUserCallback() {
@Override
public void done(User returnedUser) {
Intent loginIntent = new Intent(Register.this, LoginScreen.class);
startActivity(loginIntent);
}
});
}
}
答案 0 :(得分:1)
也许是因为你的方法中的每个if语句都被调用,这意味着DialogBuilder每次都会尝试显示对话框。
尝试使用:
if(....) {
....
}
else if(....){
.....
}
else {
.....
}
仅供参考:
只会突破封闭的
switch
,for
,while
或do-while
构造