Get numbers from EditText

放肆的年华 提交于 2019-12-04 14:52:31

The exception is:

Java.lang.NumberFormatException: unable to parse '' as integer

And it's only because there is no value in the editbox1 field.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.popupvalores);

    valor1 = (EditText) findViewById (R.id.editText1);
    myEditValue = valor1.getText().toString();

    Log.debug("logtag", myEditValue); // Here you can see the output.

    try {
        valor = Integer.parseInt(myEditValue); 
    }
    catch(Exception e) {
        Log.e("logtag", "Exception: " + e.toString());
    }
}

The code is trying to parse an empty string from the EditText '' as an int which causes an exception to be thrown.

Your example code is also missing the closing LinearLayout tag.

You are trying to access valor1 too soon, valor1 is currently an empty string. You must process the value after to user has had a chance to define something.

Try adding a button like this:

(Button) button = (Button) findViewByID(R.id.button1);
button.setOnClickListener(new OnClickListener() {
    public void onClick(View view) {
        String temp = valor1.getText().toString();
        if(temp.isEmpty() == false) {
            valor = Integer.parseInt(temp);
            Log.v("SO", "Valor = " + valor);
        }
    }
}

Use regular expression...below:

public class PopupValores extends Activity {

EditText valor1;
String myEditValue;
public static int valor;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.popupvalores);

    valor1 = (EditText) findViewById (R.id.editText1);
    myEditValue = valor1.getText().toString();
    valor = Integer.parseInt(myEditValue.replaceAll("[\\D]",""));

}

}

Your code above will definitely cause problem, because you did Integer.parseInt(myEditValue) in onCreate(), at the time your Activity is being created, your EditText is not yet filled with any text(and you didn't provide a default value in its XML definition), so it is an empty string, and Integer.parseInt(emptyString) will throw NumberFormatException.

The correct way to doing this is moving the code parsing the value of EditText to somewhere, where in response to user events, or simply try...catch Integer.parseInt().

The safest way is always to try...catch Integer.parseInt(), because we should Never Trust user's input.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!