android-fragments 运行时异常错误,片段未附加到活动

iyfamqjs  于 2022-11-14  发布在  Android
关注(0)|答案(1)|浏览(125)

我在我的片段中得到了一个运行时异常。我在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();
    }
fcg9iug3

fcg9iug31#

在onCreateView方法中初始化dbHelper,

DBHelper dbHelper;

public DashboardFragment() {}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_dashboard,container,false);
   dbHelper = new DBHelper(getActivity());
}

相关问题