edittext无法获取数据,提供空字符串

8qgya5xd  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(389)

问题是(在firstpage.java中)gettext()正在从edittext读取一个空字符串,而不是我输入的值。一旦应用程序启动,即firstpage活动开始,那么编辑文本将捕获空字符串,然后我在该字段中输入的内容将不被考虑。当按下名为click的按钮时,只捕获空字符串,因此总是给出numberformat异常。如何解决这个问题?
代码:(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");
        }

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

vlju58qv

vlju58qv1#

你写得不对。try-catch块必须在内部 setOnClickListener 因为字符串只有在按下按钮时才被使用。所以你必须这样写。

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

相关问题