Проблема в том, что (в 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);
}
});
}
XML-код для FirstPage.java:
<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");
}
Я не могу понять, что именно я делаю неправильно, пожалуйста, помогите. Заранее благодарны за Вашу помощь.