使用带游标适配器的setAdapter的空指针异常

时间:2013-08-19 15:35:13

标签: java android sqlite nullpointerexception

我正在尝试使用游标适配器但是当我调用setAdapter时我有一个空指针异常,我无法弄清楚问题是什么。代码如下:

主要片段:

public class GroupsFragment extends Fragment {

private ListView mGroupList;
private GroupAdapter mGroupAdapter;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {

    super.onCreateView(inflater, container, savedInstanceState);
    View rootView = inflater.inflate(R.layout.fragment_shedule, container, false);

    return rootView;

}

@Override
public void onActivityCreated(Bundle savedInstanceState) {

    super.onActivityCreated(savedInstanceState);

    GroupsDB databaseHelper = new GroupsDB(getActivity());

    mGroupList = (ListView) getView().findViewById(R.id.listGroup);

    Cursor cursor = databaseHelper.getGroupList();
    mGroupAdapter = new GroupAdapter(getActivity(), cursor, true);

    mGroupList.setAdapter(mGroupAdapter);   //<---NULL POINTER EXCEPTION

    databaseHelper.close();

    Button buttonSend = (Button) getView().findViewById(R.id.AddGroupButton);
    buttonSend.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) {
             AddGroup();
         }
     });

}

private void AddGroup() {

}

}

返回光标的功能,以便只包含GI.GROUP_NAME

列的名称
public Cursor getGroupList() {

    SQLiteDatabase db = this.getWritableDatabase();

    Cursor cursor = db.query(true, GI.TABLE_NAME,
                            new String[] { GI._ID , GI.GROUP_NAME },
                            null, null,
                            GI.GROUP_NAME , null, null, null);
    db.close();
    return cursor;      

}

最后是自定义适配器:

public class GroupAdapter extends CursorAdapter {

public GroupAdapter(Context context, Cursor c, Boolean f) {
    super(context, c, f);
}

@Override
public void bindView(View view, Context context, Cursor cursor) {
    TextView name = (TextView)view.findViewById(R.id.groupItem);
    name.setText(cursor.getString(1));
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    LayoutInflater inflater = LayoutInflater.from(context);
    View v = inflater.inflate(R.layout.group_list_item, parent, false);
    return v;
}
}

1 个答案:

答案 0 :(得分:0)

 mGroupList.setAdapter(mGroupAdapter);

从这一行开始,mGroupList为null,否则mGroupAdapter为null。

您应该检查ListView id

的布局文件

其他

分享您的日志猫这将有助于更清楚地了解问题。

SQLiteDatabase db = this.getWritableDatabase();

我认为你应该使用getReadableDatabase();

此处您只对数据库执行查询。