0

我如何验证 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;
}
}

有人可以帮我吗?我阅读了其他人提出的类似问题,但它并没有解决我的问题。

4

1 回答 1

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 {

}
于 2012-10-05T10:58:40.617 回答