public class Input extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText mEditText1 = (EditText)findViewById(R.id.number1i);
String val1 = mEditText1.getText().toString();
EditText mEditText2 = (EditText)findViewById(R.id.number2i);
String val2 = mEditText2.getText().toString();
double dVal1 = Double.parseDouble(val1);
double dVal2 = Double.parseDouble(val2);
}
}
This is my xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/background">
<EditText
android:id="@+id/number1i"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter your first value"
android:inputType="numberDecimal" />
<EditText
android:id="@+id/number2i"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter your second value"
android:inputType="numberDecimal" />
<TextView
android:id="@+id/output"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="22sp" />
<Button
android:id="@+id/add_marker"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Add value"
android:onClick="userInput1"
android:textSize="22sp" />
</LinearLayout>
The error:
12-05 08:57:17.113: E/AndroidRuntime(8420): Caused by: java.lang.NullPointerException
12-05 08:57:17.113: E/AndroidRuntime(8420): at com.example.whatever.input.onCreate(input.java:23)
Line 23 is
String val1 = mEditText1.getText().toString();
Any help please?
I would presume because the value could be empty?
在你的代码mEditText1.getText()
将永远是空onCreate
除非你要设置text
,从XML在它
String val1 = mEditText1.getText().toString();
if(val1 != null && val1 !=""){
double dVal1 = Double.parseDouble(val1); //+handle parse error
}
//but you should get text in onClick method
Yes it is because the String val1 = mEditText1.getText().toString();
and String val2 = mEditText2.getText().toString();
are on onCreate() they are executed before the user puts anything to the edittext try using them in an on click listener
您可以对edittext.getText()
进行空检查,并尝试将其放置在您有editext输入的代码中
Change your xml EdiText Component to :
<EditText
android:id="@+id/number1i"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter your first value"
android:text="Test Value" << Add this line
android:inputType="numberDecimal" />
Now try to run your code.
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.