我从一门课程学习Android开发,我们制作了一个笔记应用程序。我完成了它,我想添加内容并改进应用程序。我尝试在ListView中添加一个页脚,但我一直得到一个NullPointerException:
Unable to instantiate activity ComponentInfo
这是我的代码:
public TextView mTextView = (TextView) findViewById(R.id.footer_text);
final ListView listView = (ListView) findViewById(R.id.task_list);
mTaskAdapter = new TaskAdapter(mTasks);
listView.setAdapter(mTaskAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mLastPositionClicked = position;
// Toast.makeText(getApplicationContext(), "Task " + (position + 1) + " was pressed", Toast.LENGTH_SHORT).show();
Intent i = new Intent(TaskListActivity.this, TaskActivity.class);
Task task = (Task) parent.getAdapter().getItem(position);
i.putExtra(TaskActivity.EXTRA, task);
startActivityForResult(i, EDIT_TASK_REQUEST);
}
});
listView.addFooterView(mTextView);
和XML:
<TextView
android:id="@+id/footer_text"
android:text="Works!!!"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
我不知道自己做错了什么。另外,如果格式化很奇怪,我道歉。这对我来说是新的。这是要点:https://gist.github.com/najubhai/dcff0ea72feea14673a8
答案 0 :(得分:0)
在活动有窗口之前,您的电话findViewById()
应该在onCreate(Bundle)
之后或之后调用该方法。更改您的代码,如下所示:
final ListView listView = (ListView) findViewById(R.id.task_list);
// Move the addFooterView line to here, because this method
// could only be called before setting the adapter with setAdapter before KITKAT(Android 4.4)
listView.addFooterView(LayoutInflater.from(this).inflate(R.layout.your_footer_layout, null));
mTaskAdapter = new TaskAdapter(mTasks);
listView.setAdapter(mTaskAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mLastPositionClicked = position;
// Toast.makeText(getApplicationContext(), "Task " + (position + 1) + " was pressed", Toast.LENGTH_SHORT).show();
Intent i = new Intent(TaskListActivity.this, TaskActivity.class);
Task task = (Task) parent.getAdapter().getItem(position);
i.putExtra(TaskActivity.EXTRA, task);
startActivityForResult(i, EDIT_TASK_REQUEST);
}
});