findViewById时的Android NullPointerException

时间:2014-05-11 17:24:01

标签: java android nullpointerexception

当我运行我的应用程序时,我在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(或任何视图)时:

EditText editText = (EditText) findViewById(R.id.input_text);

但是,在我定义EditText时,我没有获得NPE:findViewById()就像这样:

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

我没有得到的是为什么在我明确定义视图时会出现NPE?

3 个答案:

答案 0 :(得分:2)

确保您在布局中提供的findviewbyid方法中传递正确的ID ..

否则。只需清理并构建项目。

答案 1 :(得分:0)

更改

String message = editTextInput.getText().toString();

String message = editText.getText().toString();

答案 2 :(得分:0)

这是因为findViewById()在activity_main布局中搜索,而按钮位于片段的布局fragment_main中。

将该段代码移动到片段的onCreateView()方法中:

//...

View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button buttonClick = (Button)rootView.findViewById(R.id.button);
buttonClick.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        onButtonClick((Button) view);
    }
});

请注意,现在您可以通过rootView视图访问它:

Button buttonClick = (Button)rootView.findViewById(R.id.button);

否则你会再次获得NullPointerException。