当我运行我的应用程序时,我在 log-cat 中收到此错误:
Caused by: java.lang.NullPointerException
at com.myfirstapp.myfirstapp.MainActivity.onCreate(MainActivity.java:52)
at android.app.Activity.performCreate(Activity.java:5312)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2552)
... 11 more
这是第 52 行:
String message = editTextInput.getText().toString();
到目前为止,我已经确定 NPE 必须是在定义 EditText(或任何与此相关的 View )时:
EditText editText = (EditText) findViewById(R.id.input_text);
但是,当我定义一个没有以下内容的 EditText 时,我不会得到 NPE:findViewById()
像这样的 View :
TextView desc = new TextView(this);
这是整个 onCreate()
方法:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
EditText editText = (EditText) findViewById(R.id.input_text);
Button submit = (Button) findViewById(R.id.submit);
LinearLayout layout = (LinearLayout) findViewById(R.id.layout_main);
Intent intent = new Intent(this, testActivity.class);
final TextView desc = new TextView(this);
final TextView title = new TextView(this);
String message = editText.getText().toString();
submit.setVisibility(View.VISIBLE);
submit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
editText.setVisibility(View.GONE);}});
desc.setTextSize(20);
desc.setText(message);
desc.setGravity(Gravity.LEFT | Gravity.TOP);
desc.setPadding(5, 5, 5, 5);
desc.setTextColor(getResources().getColor(R.color.black));
title.setTextSize(10);
title.setText(R.string.title_activity_dictionary);
title.setGravity(Gravity.LEFT | Gravity.TOP);
title.setPadding(5, 5, 5, 5);
title.setTextColor(getResources().getColor(R.color.black));
layout.addView(desc);
layout.addView(title);
}
我不明白的是,当我明确定义 View 时,为什么会有 NPE?
最佳答案
确保您在布局中可用的 findviewbyid 方法中传递了正确的 id。
否则。只需清理并构建项目即可。
关于java - Android findViewById 时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23595675/