将片段添加到我的项目后,getWritableDatabase 出现 NullPointerException
我有一个正在工作的项目,现在我想升级布局,并且正在尝试添加片段(蜂窝前),但现在似乎我在连接到数据库时遇到了一些麻烦,并且我收到了 NullPointerException :
ERROR/AndroidRuntime(27294):
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:118)
ERROR/AndroidRuntime(27294):
at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:187)
我相信这与我发送给数据库构造函数的上下文有关。
这是我的班级:
public class ShowFragment extends ListFragment {
ArrayList<String> results = new ArrayList<String>();
private SQLiteDatabase db;
WorkTrackdb workdb = new WorkTrackdb(getActivity());
private ViewGroup mRootView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Cursor c = getYears();
//some code here
}
Cursor getYears() {
db = workdb.getReadableDatabase();
String years[] = {"year"};
Cursor cursor = db.query(WorkTrackdb.TABLE_NAME, years, null,
null, null, null,"year DESC");
return cursor;
}
I had a working project, now I wanted to upgrade the layout and I'm trying to add Fragments (pre honeycomb), but now seems like I'm having some troubles connecting to my DB, and I'm getting NullPointerException
:
ERROR/AndroidRuntime(27294):
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:118)
ERROR/AndroidRuntime(27294):
at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:187)
I believe it has something to do with the Context i'm sending to the database constructor.
here is my class:
public class ShowFragment extends ListFragment {
ArrayList<String> results = new ArrayList<String>();
private SQLiteDatabase db;
WorkTrackdb workdb = new WorkTrackdb(getActivity());
private ViewGroup mRootView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Cursor c = getYears();
//some code here
}
Cursor getYears() {
db = workdb.getReadableDatabase();
String years[] = {"year"};
Cursor cursor = db.query(WorkTrackdb.TABLE_NAME, years, null,
null, null, null,"year DESC");
return cursor;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试使用 SQLiteDatabase.openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags) 代替。
我不确定您是否需要在
onCreate()
内实例化 WorkTrackdb workdb = new WorkTrackdb(getActivity());Try using
SQLiteDatabase.openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags)
instead.I'm not sure maybe you need to
instantiate WorkTrackdb workdb = new WorkTrackdb(getActivity());
inside theonCreate()