EditText无法获取数据,给出了null字符串



问题是(在FirstPage.java中(getText((正在从EditText中读取一个空字符串,而不是我输入的值。一旦应用程序启动,即FirstPage活动开始,编辑文本就会捕获空字符串,然后我在该字段中输入的任何内容都不会被考虑。然后,当按下名为click的按钮时,只捕获空字符串,因此总是出现NumberFormat Exception。如何解决这个问题?

代码:(FirstPage.java(

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first_page);
Click = findViewById(R.id.click);
Text = findViewById(R.id.text);
try {
number = Integer.parseInt(Text.getText().toString());
}catch (NumberFormatException e){
number = 2; //the problem is here getText() is always getting null string
//and hence catch statement is always getting executed
}
Click.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent ii= new Intent(FirstPage.this, MainActivity.class);
ii.putExtra("value", number);
startActivity(ii);
}
});
}

FirstPage.java的XML代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".FirstPage">
<EditText
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="20dp"
android:hint="Enter no of ques"
android:layout_marginTop="30dp"/>
<Button
android:id="@+id/click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:text="Click"/>
</LinearLayout>

MainActivity.class代码部分:

Bundle bundle = getIntent().getExtras();
if (bundle != null) {
value = bundle.getInt("value");
}

我不明白我到底做错了什么,请帮帮我。感谢您提前提供的帮助。

您的编写方式不对。try-catch块必须在setOnClickListener内,因为只有在按下按钮时才会使用String。所以你必须这样写。

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first_page);
Click = findViewById(R.id.click);
Text = findViewById(R.id.text);

Click.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
number = Integer.parseInt(Text.getText().toString());
} catch (NumberFormatException e){
number = 2; 
}
Intent ii= new Intent(FirstPage.this, MainActivity.class);
ii.putExtra("value", number);
startActivity(ii);
}
});
}

最新更新