-2

I am new to database in Android but now I know the way to apply CRUD (Create, Read, Update, Delete) operations on an activity but in case of fragments, getWritableDatabase() is not working. I would like to know the best way to apply CRUD operations in fragments. In activities, I made a class to handle database operations and then made its' object in the activity and was able to work on it thereafter.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Sarthak Sharma
  • 105
  • 1
  • 4

2 Answers2

0

Try

DbHelper helper = DbHelper.getInstance(getContext());
SQLiteDatabase db = helper.getWritableDatabase();` 

instead

touhid udoy
  • 4,005
  • 2
  • 18
  • 31
0

Here I tried to illustrate calling db from fragment class :

SQLiteDatabase db = context.getWritableDatabase(); // 'this' for activity

Initialize db object inside onAttach() or onActivityCreated() any other method : [onAttach() is preferable]

public Cursor getAllData() {
  Cursor result = db.rawQuery("SELECT * FROM "+ TABLE_NAME, null);
  return result; 
}

Tips: You should use these type of db calls into the background threads, not to invoke or block the UI thread which will result a better performance.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
A S M Sayem
  • 2,010
  • 2
  • 21
  • 28