dimanche 8 novembre 2015

Getting an Android (Java) field to be empty and not -1

I am making an Android app that accepts an age in one of its fields, when the user does not specify an age at first the field stays blank but if the user does add an age but then goes back to edit it later to nothing it leaves -1 I have thought about making age a String and converting it to an Int on every if statement on succession but that's bad programming. Any ideas? Thanks!

 private void finishEditing() {
    String newText = editor.getText().toString().trim();
    String newName = editorName.getText().toString().trim();
    int newAge111 = -1;

    boolean ageValid = true;
    boolean finished = true; //everthings validated and perfect to be saved
    try {
        String ageString = editorAge.getText().toString();
        newAge111 = Integer.parseInt(ageString);
    } catch (NumberFormatException e) {
        ageValid = false;
    }

    switch (action) {
        case Intent.ACTION_INSERT:
            if (newText.length() == 0 && newName.length() == 0) {
                //Toast.makeText(this, "Age must be an Integer", Toast.LENGTH_SHORT).show();
                setResult(RESULT_CANCELED);
            }else {
                insertNote(newText, newName, newAge111);
            }
            break;
        case Intent.ACTION_EDIT:
            if (newText.length() == 0 && newName.length() == 0) {
                deleteNote();
            } else if (oldText.equals(newText) && oldName.equals(newText)) {
                setResult(RESULT_CANCELED);
            } else if (!newName.matches("[a-zA-Z]+")) { // check if numbers are in name field
                editorName.setError(Html.fromHtml("<font color='red'>Name must not contain a number</font>"));
                finished = false;
            } else if (newAge111 < 0) {
                //String ageString = "" + newAge111;
                Toast.makeText(this, "NOT WORKING", Toast.LENGTH_SHORT).show();

            } else {
                updateNote(newText, newName, newAge111);
            }
    }

    if (finished) finish();
}

 private void insertNote(String noteText, String newName, int newAge) {
    ContentValues values = new ContentValues();
    values.put(DBOpenHelper.NOTE_TEXT, noteText);
    values.put(DBOpenHelper.NOTE_NAME, newName);
    values.put(DBOpenHelper.NOTE_AGE, newAge);
    getContentResolver().insert(NotesProvider.CONTENT_URI, values);
    setResult(RESULT_OK);
}

Aucun commentaire:

Enregistrer un commentaire