无法从edittext获取字符串值

时间:2014-08-12 08:21:45

标签: android android-edittext

我正在尝试使用jdbc连接器将数据发送到mysql数据库。我使用EditText为用户填写他们的信息。我正在尝试从EditText获取字符串值,但它们返回null。这是我的acvitivity类,我无法弄清楚为什么字符串值返回空字符串。

String setFirstname = "";
String setLastname = "";
String setCountry = "";
String setCity = "";
String setCompany = "";
String setAddress = "";
String setEmail = "";
String setUsername = "";
String setPhone = "";
String setPassword = "";
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.register);
    TextView loginScreen = (TextView) findViewById(R.id.link_to_login);
    final EditText getFirstname = (EditText) findViewById(R.id.reg_firstname);
    setFirstname = getFirstname.getText().toString().trim();
    final EditText getCountry = (EditText) findViewById(R.id.reg_country);
    setCountry= getCountry.getText().toString().trim();
    final EditText getLastname = (EditText) findViewById(R.id.reg_lastname);
    setLastname= getLastname.getText().toString().trim();
    final EditText getCity = (EditText) findViewById(R.id.reg_city);
    setCity= getCity.getText().toString().trim();
    final EditText getCompany = (EditText) findViewById(R.id.reg_company);
    setCompany= getCompany.getText().toString().trim();
    final EditText getAddress = (EditText) findViewById(R.id.reg_address);
    setAddress= getAddress.getText().toString().trim();

    Button reg = (Button) findViewById(R.id.btnRegister);
    reg.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

           new readySQL().execute();
        }
    });

    // Listening to Login Screen link
    loginScreen.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            // Closing registration screen
            // Switching to Login Screen/closing register screen
            finish();
        }
    });

2 个答案:

答案 0 :(得分:4)

创建编辑文本时,您将获得字符串。当时显然是空的。用户尚未输入任何内容。 相反,你应该这样做

Button reg = (Button) findViewById(R.id.btnRegister);
reg.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

       // Fetch strings from edit texts here and check if they are not empty

       new readySQL().execute();
    }
});

答案 1 :(得分:0)

初始化时不应该获取editText值,而是必须在editText上设置一个侦听器以检测值何时更改,如下所示:

editText.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(final CharSequence s, final int start,
                final int before, final int count) {
             //collect the changed value
             setValue=(editText.getText().toString().trim());

        }

        @Override
        public void beforeTextChanged(final CharSequence s,

        }

        @Override
        public void afterTextChanged(final Editable s) {

        }
    });