Felipe Hield Felipe Hield - 5 months ago 7
Java Question

Checking/Storing inputs from EditTexts(Android/Java)

I am trying to learn android in java but I m stuck. Here is my method to get values from EditText fields.

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);
}


This is the xml for button.

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


What I want to do is following. If someone leaves EditText Null or enters a non-integer value to numberfield I want to DISPLAY that in android but System.out.println() does not display anything. If the previous case does not happen I want to save the variables to a local database. How can I do that?

Answer

Try something like this:

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();
        }
    }
}