检查/存储来自EditTexts的输入(Android / Java)

时间:2016-07-01 20:06:01

标签: java android eclipse

我正在尝试在java中学习android,但我陷入困境。这是我从EditText字段获取值的方法。

public void sendFeedback(View button) { 


      System.out.println("Do not fail");
           final EditText nameField = (EditText) findViewById(R.id.Name);
           String name = nameField.getText().toString();
           final EditText numberField = (EditText) findViewById(R.id.Cost);
           String test=numberField.getText().toString();
           Integer x = Integer.parseInt(test.trim());
           System.out.println(x);
           System.out.println(name);
         }

这是按钮的xml。

<Button
    android:id="@+id/ButtonSendFeedback"
    android:layout_height="wrap_content"
    android:text="Submit"
    android:onClick="sendFeedback"
    android:layout_width="fill_parent">
</Button>

我想做的是跟随。如果有人离开EditText Null或输入非整数值到numberfield我想在android中显示,但System.out.println()不显示任何内容。如果前一种情况没有发生,我想将变量保存到本地数据库。我怎么能这样做?

4 个答案:

答案 0 :(得分:1)

尝试这样的事情:

public void sendFeedback(View button) {
    Toast.makeText(this, "Do not fail", Toast.LENGTH_SHORT).show();
    final EditText nameField = (EditText) findViewById(R.id.Name);
    if(nameField != null) {
        String name = nameField.getText().toString();

        if (!name.isEmpty()) {
            Toast.makeText(this, "Name: " + name, Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "Namefield is empty!" , Toast.LENGTH_SHORT).show();
        }
    }
    final EditText numberField = (EditText) findViewById(R.id.Cost);
    if(numberField != null) {
        String test = numberField.getText().toString();
        if(!test.isEmpty()) {
            int x = Integer.parseInt(test.trim());
            Toast.makeText(this, "Cost: " + x, Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "You haven't entered a number", Toast.LENGTH_SHORT).show();
        }
    }
}

答案 1 :(得分:0)

答案 2 :(得分:0)

System.out.println将邮件记录到console。因此,您无法使用它来显示UI中的错误。要在Android中显示错误,您应该使用以下内容:

答案 3 :(得分:0)

System.out.println()打印到控制台。尝试使用Toast通知用户无效输入