在Android应用程序中访问文本字段时出错

时间:2012-11-02 14:51:12

标签: android

我在下面的示例中将EditText e1的值视为null。所以它抛出空指针异常。我在下面的MainActivity中写道,并在单击按钮时调用函数calculateSquare。我错过了什么吗?

public void calculateSquare(View view) {
    setContentView( R.layout.activity_main);
    EditText e1=(EditText) findViewById(R.id.editText1);
    int number = Integer.parseInt(e1.getText().toString());
    int square=number * number;
    TextView e2=(TextView) findViewById(R.id.textView2);
    e2.setText(square);
}

activity_main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="25dp"
    android:text="@string/hello_world"
    tools:context=".MainActivity" />
<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/textView1"
    android:layout_marginLeft="32dp"
    android:layout_marginTop="52dp"
    android:layout_toLeftOf="@+id/textView1"
    android:ems="10"
    android:inputType="number" />
<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/editText1"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="29dp"
    android:text="CalculateSquare" 
    android:onClick="calculateSquare"/>
<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignTop="@+id/editText1"
    android:layout_marginRight="36dp"
    android:text="Square"
    android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>

1 个答案:

答案 0 :(得分:5)

您需要将String作为参数传递给setText()。 将您的代码更改为:

e2.setText(square+"");

当您调用setText(int)时,系统将按给定的id(int)查找String资源,该资源需要从R类提供。

e2.setText(R.string.mystring);

关于空指针,尝试清理项目,然后将启动移动到onCreate()方法。

@Override
public void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  setContentView( R.layout.activity_main);
  EditText e1=(EditText) findViewById(R.id.editText1);
  TextView e2=(TextView) findViewById(R.id.textView2);
}

public void calculateSquare(View view) {
  int number;
  if (e1.getText().toString().length()>0){
     number = Integer.parseInt(e1.getText().toString());
     int square=number * number;
     e2.setText(square+"");
  }
}

您始终需要检查是否在edittext中输入了某些内容,因为无法将空字符串转换为int。