getCount()方法中的nullpointerexception

时间:2014-10-24 06:18:08

标签: android

我想使用cursoradapter从数据库填充listview。我在getCount方法中遇到了NullPointerException。

提前谢谢你:D

下面是我的游标适配器代码。

public class tasksCursorAdapter extends CursorAdapter {

Cursor cursor;

public tasksCursorAdapter(Context context, Cursor c, int flags) {
    super(context, c, flags);
    this.cursor = c;
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {

    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View retView = inflater.inflate(R.layout.single_row, parent, false);
    return retView;
}

@Override
public int getCount() {
   return cursor.getCount();
}

@Override
public void bindView(View view, Context context, Cursor cursor) {

    tasks_Database_Operations tasksDatabaseOperations = new tasks_Database_Operations(context);
    tasksDatabaseOperations.getWritableDatabase();
    TextView tvTask, tvDate, tvTime;
    tvTask = (TextView) view.findViewById(R.id.task_added);
    tvDate = (TextView) view.findViewById(R.id.date_added);
    tvTime = (TextView) view.findViewById(R.id.time_added);
    tvTask.setText(cursor.getString(1));
    tvDate.setText(cursor.getString(2));
    tvTime.setText(cursor.getString(3));

}
}

这就是我实现适配器的地方

public class tasksListFrag extends Fragment implements View.OnClickListener {

ListView taskslist;
Button delete;
Cursor cursor;

tasksCursorAdapter adapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.tasks_list_frag, container, false);
    Log.d("HirakDebug", "tasksListFrag View Created");
    taskslist = (ListView) view.findViewById(R.id.tasks_list);
    adapter = new tasksCursorAdapter(getActivity(), cursor, CursorAdapter.FLAG_AUTO_REQUERY);
    taskslist.setAdapter(adapter);
    adapter.notifyDataSetChanged();

2 个答案:

答案 0 :(得分:0)

您的光标应为null。您应该使用内置游标,而不是使用自定义的cursor。删除班级中的Cursor声明以及this.cursor = c;。同时删除getCount的覆盖。然后它应该正常工作,这是因为默认情况下CursorAdapter实现了游标,这就是为什么它被称为cursoradapter。只需确保光标有一些行

答案 1 :(得分:0)

adapter = new tasksCursorAdapter(getActivity(), cursor, CursorAdapter.FLAG_AUTO_REQUERY);

您的cursor未在此处初始化,且为nullCursorAdapter需要实际的Cursor