我在我的片段中得到了一个运行时异常。我在DBHelper类的初始化过程中传递了上下文。我想显示数据库中的条目数。
片段代码:
DBHelper dbHelper = new DBHelper(requireContext());
public DashboardFragment() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_dashboard,container,false);
TextView textView1 = view.findViewById(R.id.text_top);
TextView textView2 = view.findViewById(R.id.text_top2);
TextView recordEntries = view.findViewById(R.id.record_entries);
recordEntries.setText(dbHelper.countEntries());
DBHelper程式码:
public DBHelper(@Nullable Context context) {
super(context, Params.DB_NAME , null, Params.DB_VERSION);
}
public int countEntries()
{
String query = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query,null);
return cursor.getCount();
}
1条答案
按热度按时间fcg9iug31#
在onCreateView方法中初始化dbHelper,