我想调用此方法getAllData();从Fragment,这个方法从SQlite数据库返回游标数据,我想在我的Fragment中使用该数据来创建listView,我使用这些代码行来访问该数据
PackagesDbHelper mydb = new PackagesDbHelper(getActivity());
Cursor result = mydb.getAllData();
但是在应用启动时,我收到此错误"遗憾的是应用已停止"但如果我排除这行代码
Cursor result = mydb.getAllData();
我的应用运行正常
PackagesDbHelper
public class PackagesDbHelper extends SQLiteOpenHelper {
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor result = db.rawQuery("SELECT * FROM " + PackagesContract.ufoneEntry.TABLE_NAME, null);
return result;
}
}
PackagesFragment
public class PackagesFragment extends Fragment {
private PackagesAdapter packagesAdapter;
PackagesDbHelper mydb = new PackagesDbHelper(getActivity());
@Override
public void onCreate(Bundle savedInstanceState) {
Cursor result = mydb.getAllData();
super.onCreate(savedInstanceState);
}
}
答案 0 :(得分:3)
下面:
PackagesDbHelper mydb = new PackagesDbHelper(getActivity());
行导致问题,因为在类级调用getActivity()
将返回无效的Activity Context。
在mydb
或其他任何方法中初始化onCreate
对象:
mydb = new PackagesDbHelper(getActivity());
Cursor result = mydb.getAllData();
答案 1 :(得分:2)
问题在于
SQLiteDatabase db = this.getWritableDatabase();
这个方法应该按上下文调用。
public Cursor getAllData() {
SQLiteDatabase db = context.getWritableDatabase();
Cursor result = db.rawQuery("SELECT * FROM " + PackagesContract.ufoneEntry.TABLE_NAME, null);
return result;
}