我正在尝试为Android创建一个程序,该程序将以文本形式读取,然后打印出来,jsut以便习惯使用Android的I / O.但是,每当我在AVD上运行它时,它在LogCat中返回一个错误,说我的代码中存在NullPointerException,因此它无法实例化活动ComponentInfo"。
我无法找到我所指的任何无效的地方。
这是我的代码:
import android.app.*;
import android.os.*;
import android.view.View;
import android.view.View.*;
import android.widget.*;
public class ButtonTestActivity extends Activity {
TextView tv = (TextView) findViewById(R.id.textView1);
EditText et = (EditText) findViewById(R.id.edittext);
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.Enter);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
tv.setText(et.getText().toString());
}
});
}
}
这是我的XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<Button
android:id="@+id/Enter"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<EditText
android:id="@+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
有谁知道造成这种情况的原因是什么?非常感谢。
答案 0 :(得分:16)
您需要在onCreate中实例化视图,并且在setContentView之后,在您通过setContentView方法设置Activities布局之前,Activity不知道您要引用哪些视图。如果这不能解决问题,那么如果您从LogCat发布堆栈跟踪,那么确切的行号是已知的。
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.textView1);
EditText et = (EditText) findViewById(R.id.edittext);
Button b = (Button) findViewById(R.id.Enter);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
tv.setText(et.getText().toString());
}
});
}
答案 1 :(得分:0)
我认为问题是由创建类实例时直接初始化的两个字段tv
和et
引起的。
您应该使用“按钮b”在onCreate
方法中移动两个字段的初始化。
答案 2 :(得分:0)
在设置内容之前,您尝试实例化textview和EditText,这就是为什么你有空指针异常的原因
感谢
答案 3 :(得分:0)
空指针异常意味着您正在引用尚未创建的内容
setContentView
通过变量tv
和et
创建必要的字段
因此,您需要在tv
后et
和setContentView
。
答案 4 :(得分:0)
是的,除了以上答案之外,我给出了这个错误,因为在onCreate方法之前定义一个变量:
boolean in = true;
@Override
protected void onCreate .......