I am getting this error
A SQLiteConnection object for database '/data/data/com.*******/databases/myDatabase' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
I closed all cursors and database but I still get this error
This is my Database helper class:
public static DatabaseHelper getInstance(Context ctx) {
if (mInstance == null) {
mInstance = new DatabaseHelper(ctx.getApplicationContext());
}
return mInstance;
}
private DatabaseHelper(Context context) {
super(context, DB_NAME, null, 1);
if (android.os.Build.VERSION.SDK_INT >= 17) {
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
} else {
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
}
this.context = context;
...
}
public void create() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
//do nothing - database already exist
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkDataBase() {
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
private void copyDataBase() throws IOException {
InputStream myInput = context.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public boolean open() {
try {
String myPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
return true;
} catch (SQLException sqle) {
db = null;
return false;
}
}
@Override
public synchronized void close() {
if (db != null)
db.close();
super.close();
}
public List<MyPojo> getCat() {
List<MyPojo> pojos = new ArrayList<>();
try {
String query = "SELECT DISTINCT _id, CatA FROM Categories ORDER BY _id ASC ";
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
Cursor cursor = db.rawQuery(query, null);
while (cursor.moveToNext()) {
int catID = cursor.getInt(0);
String catName = cursor.getString(1);
MyPojo pojo = new MyPojo(catID, catName);
pojos.add(pojo);
}
cursor.close();
} catch(Exception e) {
Log.d("DB", e.getMessage());
}
return pojos;
}
and this is how I use them in my code:
private List<MyPojo> getCat() {
List<MyPojo> pojos = new ArrayList<>();
DatabaseHelper db = DatabaseHelper.getInstance(getContext());
try {
db.create();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
if (db.open()) {
pojos = db.getCat();
}
}finally {
db.close();
}
return pojos;
}
I have also tried this link but still no luck. I can't seem to find where exactly the leak is happening.
What am I doing wrong?