简体   繁体   English

从EditText获取数字

[英]Get numbers from EditText

I know that his have been asked a few times, but I have been trying everything I have found with no luck. 我知道他曾被问过几次,但是我一直在尝试一切没有运气的事情。 I'm still having a error. 我还有错误。 Here's my code. 这是我的代码。

xml XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:background="@android:color/transparent"
android:gravity="center"
android:orientation="vertical" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Write item value."
    android:textColor="@android:color/black"
    android:textSize="25dp" />

<EditText
    android:id="@+id/editText1"
    android:layout_width="80dp"
    android:layout_height="wrap_content"
    android:layout_marginBottom="202dp"
    android:ems="10"
    android:hint="Value"
    android:inputType="number" >

    <requestFocus />
</EditText>

java java的

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);   <<<<Line 20

    }
}

LogCat logcat的

05-08 21:02:10.023: W/dalvikvm(6074): threadid=1: thread exiting with uncaught exception (group=0x40020578)
05-08 21:02:10.039: E/AndroidRuntime(6074): FATAL EXCEPTION: main
05-08 21:02:10.039: E/AndroidRuntime(6074): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dc.maker/com.dc.maker.PopupValores}: java.lang.NumberFormatException: unable to parse '' as integer
05-08 21:02:10.039: E/AndroidRuntime(6074):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
05-08 21:02:10.039: E/AndroidRuntime(6074):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
05-08 21:02:10.039: E/AndroidRuntime(6074):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
05-08 21:02:10.039: E/AndroidRuntime(6074):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
05-08 21:02:10.039: E/AndroidRuntime(6074):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-08 21:02:10.039: E/AndroidRuntime(6074):     at android.os.Looper.loop(Looper.java:130)
05-08 21:02:10.039: E/AndroidRuntime(6074):     at android.app.ActivityThread.main(ActivityThread.java:3687)
05-08 21:02:10.039: E/AndroidRuntime(6074):     at java.lang.reflect.Method.invokeNative(Native Method)
05-08 21:02:10.039: E/AndroidRuntime(6074):     at java.lang.reflect.Method.invoke(Method.java:507)
05-08 21:02:10.039: E/AndroidRuntime(6074):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
05-08 21:02:10.039: E/AndroidRuntime(6074):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
05-08 21:02:10.039: E/AndroidRuntime(6074):     at dalvik.system.NativeStart.main(Native Method)
05-08 21:02:10.039: E/AndroidRuntime(6074): Caused by: java.lang.NumberFormatException: unable to parse '' as integer
05-08 21:02:10.039: E/AndroidRuntime(6074):     at java.lang.Integer.parseInt(Integer.java:362)
05-08 21:02:10.039: E/AndroidRuntime(6074):     at java.lang.Integer.parseInt(Integer.java:332)
05-08 21:02:10.039: E/AndroidRuntime(6074):     at com.popupclass.PopupValores.onCreate(PopupValores.java:20)
05-08 21:02:10.039: E/AndroidRuntime(6074):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-08 21:02:10.039: E/AndroidRuntime(6074):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
05-08 21:02:10.039: E/AndroidRuntime(6074):     ... 11 more

I'm trying to get a int from the EditText and then use it in other class to determinate a value of something. 我试图从EditText中获取一个int,然后在其他类中使用它来确定某个值。 Can someone tell me what I'm doing wrong? 有人能告诉我我做错了什么吗?

Thanks 谢谢

The exception is: 例外是:

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

And it's only because there is no value in the editbox1 field. 这只是因为editbox1字段中没有值。

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

You are trying to access valor1 too soon, valor1 is currently an empty string. 您试图过早访问valor1valor1当前是一个空字符串。 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);
        }
    }
}

The code is trying to parse an empty string from the EditText '' as an int which causes an exception to be thrown. 代码试图将EditText'中的空字符串解析为int,这会导致抛出异常。

Your example code is also missing the closing LinearLayout tag. 您的示例代码也缺少结束LinearLayout标记。

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 . 上面的代码肯定会引起问题,因为你在onCreate()中使用了Integer.parseInt(myEditValue) ,在创建Activity时,你的EditText还没有填充任何文本(并且你没有提供默认值在它的XML定义中),因此它是一个空字符串,而Integer.parseInt(emptyString)将抛出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() . 执行此操作的正确方法是将解析EditText值的代码移动到某处,其中响应用户事件,或者只是try...catch Integer.parseInt()

The safest way is always to try...catch Integer.parseInt() , because we should Never Trust user's input . 最安全的方法总是try...catch Integer.parseInt() ,因为我们应该永远不要相信用户的输入

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM