我在childActivity intent中得到了null引用异常。我是android开发的新手。请帮我解决这个问题。我正在做什么来将数据从ParentActivity发送到ChildActivity。
ParentActivity:我在ParentActivity中有3个EditText字段。我想在ChildActivity中显示这3个字段。有一个按钮控件,所以当我点击它时,它必须从ParentActivity切换到ChildActivity。
public class ParentActivity extends Activity {
private EditText EmpId;
private EditText EmpName;
private EditText Gender;
private Button btnShowInfo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_parent);
InitializeControls();
}
private void InitializeControls() {
EmpId = (EditText) findViewById(R.id.editText1);
EmpName = (EditText) findViewById(R.id.editText2);
Gender = (EditText) findViewById(R.id.editText3);
btnShowInfo = (Button) findViewById(R.id.button1);
final Context context = this;
btnShowInfo.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent ParentIntent = new Intent(context, ChildActivity.class);
ParentIntent.putExtra("Eid", EmpId.getText().toString());
ParentIntent.putExtra("EName", EmpName.getText().toString());
ParentIntent.putExtra("EGender", Gender.getText().toString());
startActivity(ParentIntent);
}
});
}
}
ChildActivity ::它必须显示我在ParentActivity中输入的值。
public class ChildActivity extends Activity {
private TextView txtView1;
private TextView txtView2;
private TextView txtView3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_child);
InitializeControls();
}
private void InitializeControls() {
txtView1 = (TextView) findViewById(R.id.editText1);
txtView2 = (TextView) findViewById(R.id.editText2);
txtView3 = (TextView) findViewById(R.id.editText3);
GetDataFromIntent();
}
private void GetDataFromIntent() {
Bundle extras = getIntent().getExtras();
if (extras == null) {
txtView1.setText("No data is received.");
} else {
txtView1.setText(extras.getString("Eid"));
txtView2.setText(extras.getString("EName"));
txtView3.setText(extras.getString("EGender"));
}
}
}
异常::这是我在控制台窗口中获得的内容。
01-05 15:04:46.210: E/AndroidRuntime(1658): Caused by: java.lang.NullPointerException
01-05 15:04:46.210: E/AndroidRuntime(1658): at com.example.androidexample1.ChildActivity.GetDataFromIntent(ChildActivity.java:36)
01-05 15:04:46.210: E/AndroidRuntime(1658): at com.example.androidexample1.ChildActivity.InitializeControls(ChildActivity.java:26)
01-05 15:04:46.210: E/AndroidRuntime(1658): at com.example.androidexample1.ChildActivity.onCreate(ChildActivity.java:19)
我是android世界的新手。请帮忙。
答案 0 :(得分:0)
因此导致问题的代码行是:
txtView1.setText(extras.getString("Eid"));
空指针异常本质上意味着您正在尝试在null的内容上调用函数。在这种情况下,它可以是txtView1
或extras
。当您检查extra是否为null时,它实际上必须是null的txtView1。每Android documents,findViewById
返回:
返回
The view that has the given id in the hierarchy or null
因此,如果拼写错误的文本标签,可能会导致此问题。检查的一个好方法是在错误发生之前添加此权限。
Log.v("Child","txtView1="+txtView1);