我正在尝试使用游标适配器,但在调用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;
}
}
mGroupList.setAdapter(mGroupAdapter);
从这一行中,mGroupList为null,否则mGroupAdapter为null。
您应该检查您的布局文件中的ListView id
其他
分享你的日志猫这将有助于更清楚地理解问题。
SQLiteDatabase db = this.getWritableDatabase();
我认为您应该使用getReadableDatabase();
这里您只对DB执行查询。