Edittext字符串验证问题

时间:2012-09-20 14:09:39

标签: android-edittext

如何验证EditText是否具有值(即,它不为空或不为空)。我编写了以下代码,将键入EditText的字符串值分配给String对象,但验证它不是空的对我来说是一个问题。无论何时我运行它,我都会得到一个NullPointerException

public class LoginFragment extends SherlockFragment {
EditText e1;
EditText e2;
Button b;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInatanceState) {
    View view = inflater.inflate(R.layout.login_layout, container, false);

    e1 = (EditText) view.findViewById(R.id.reg_email);
    e2 = (EditText) view.findViewById(R.id.reg_password);

    b = (Button) view.findViewById(R.id.btnLogin);
    b.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            String mEmail = e1.getText().toString(); // NullPointerException
            String pwrd = e2.getText().toString();

            if ((mEmail.equals(null)) || (pwrd.equals(null))) {
                AlertDialog.Builder build = new AlertDialog.Builder(
                        getActivity());
                build.setMessage("Please enter your login details");
                build.setCancelable(false);

                build.setPositiveButton("Ok",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                dialog.cancel();

                            }
                        });
                AlertDialog alert = build.create();
                alert.show();
            } else {
                Toast.makeText(getActivity(), "Welcome", Toast.LENGTH_SHORT)
                        .show();
                Intent intent = new Intent(getActivity(), Home.class);
                startActivity(intent);
            }

        }
    });
    return view;
}
}

有人可以帮我这个吗?我在其他人的问题上读了一个类似的问题,但它并没有解决我的问题。

1 个答案:

答案 0 :(得分:0)

您不需要在字符串中取值。对此的解决方案如下。 在课程级别定义

EditText username;
EditText password;

然后按照

进行操作
username = (EditText) findViewById(R.id.User_name_value);
password = (EditText) findViewById(R.id.password_value);
if (username.getText().toString().equals("") || password.getText().toString().equals("")) 
{
    // Log.i("TAG!","Inside if condition");
    Toast.makeText(this, user_text, Toast.LENGTH_SHORT).show();
} else {

}