我希望从EditText
得到一个double值,你只能在numberDecimal和numberSigned中找到它。
我想:
EditText editText1 = (EditText)findViewById(R.id.edittext1)
double double1 = Double.parseDouble(editText1.getText().toString());
但是 logcat说这个double = ""
和应用程序崩溃了
logcat的:
08-29 20:52:24.148 22688-22688/test.com.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity
ComponentInfo{test.com.app/test.com.app.Main}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2295)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
at android.app.ActivityThread.access$700(ActivityThread.java:159)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at java.lang.StringToReal.parseDouble(StringToReal.java:244)
at java.lang.Double.parseDouble(Double.java:295)
at test.com.app.Graph.yWerte(Graph.java:188)
at test.com.app.Graph.getDataFromReceiver(Graph.java:184)
at test.com.app.Main.onCreate(Main.java:30)
at android.app.Activity.performCreate(Activity.java:5372)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
at android.app.ActivityThread.access$700(ActivityThread.java:159)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:1)
editText1.getText()
是null
。试试这个:
CharSequence cs = editText1.getText();
double double1 = cs == null ? -1.0 : Double.parseDouble(cs.toString());
如果你想在你输入一个不可解析的双精度时也避免NumberFormatException
,你可以写:
double double1 = -1.0; // invalid!
try {
double1 = Double.parseDouble(editText1.getText().toString());
} catch(RuntimeException ignored) {
// NPE or parsing failed, double1 == -1.0
}
一般来说,捕捉(并且忽略)RuntimeException
并不是一种好的做法,但是由于特定的API,这个例子没问题。
编辑:在发布堆栈跟踪后更新
编辑2:更新以更正解析问题