我的注册工作正常,但我想验证字段(EditText)是否为空,如果我点击注册应用程序崩溃,如果我留下一个空字段,它也会崩溃..
public class register extends AppCompatActivity {
AlertDialog.Builder builder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
builder = new AlertDialog.Builder(register.this);
final EditText etAge = (EditText) findViewById(R.id.etAge);
final EditText etName = (EditText) findViewById(R.id.etName);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final Button bRegister = (Button) findViewById(R.id.bRegister);
bRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String name = etName.getText().toString();
final String username = etUsername.getText().toString();
final int age = Integer.parseInt(etAge.getText().toString());
final String password = etPassword.getText().toString();
//test of error
if (name.equals("") || username.equals("") || age == 0 || password.equals("")) {
builder.setTitle("Something Went Wrong");
builder.setMessage("Please fill in all the fileds").setPositiveButton("OK", null).create().show();
} else {
Response.Listener<String> responseListener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
Intent intent = new Intent(register.this, login.class);
register.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(register.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(name, username, age, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(register.this);
queue.add(registerRequest);
}
}
});
}
答案 0 :(得分:0)
Integer age =null;
if(!etAge.getText().toString().trim().equals(""))
{
age=Integer.parseInt(etAge.getText().toString());
}
final String password = etPassword.getText().toString();
//test of error
if (name.equals("") || username.equals("") || age == null || password.equals("")) {
builder.setTitle("Something Went Wrong");
builder.setMessage("Please fill in all the fileds").setPositiveButton("OK", null).create().show();
return ;
}