-1

I am getting a runtime exception in my fragment. I have passed the context during the initialization of my DBHelper class. I want to display the number of entries in database.

Fragment Code:

    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 Code:

    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();
    }
  • 2
    Does this answer your question? [Fragment MyFragment not attached to Activity](https://stackoverflow.com/questions/10919240/fragment-myfragment-not-attached-to-activity) – a_local_nobody Apr 08 '22 at 10:36

1 Answers1

0

Initialise dbHelper in onCreateView method,

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());
}
Jinal Patel
  • 229
  • 2
  • 7