Databaseobjectnotclosedexception Even With Try-with-resources
In my application, various components will connect try to fetch photo and music information from the android MediaStore. I run into DatabaseObjectNotClosedExcepton like this: ? E/C
Solution 1:
As usual, reading the Android source will help a lot.
CursorLeakDetecter
is used in the class ActivityThread
, here is the important bit:
// ...if(uriMap.get(uri) == null) {
uriMap.put(uri,1);
}else {
uriMap.put(uri,uriMap.get(uri)+1);
}
// when uri>5, print log informationif(uriMap.get(uri) >= 5) {
Log.e("CursorLeakDetecter", "PossibleCursorLeak:"+uri+",QueryCounter:"+uriMap.get(uri), stackTrace);
}
// ...
So the assumption is that a query, when requested 5 times, is a potential leak. Looking back at the method above, let's check how the list of photo albums is retrieved:
returnnewCursorFields(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, PHOTO_PROJECTION,
MediaStore.Images.Media.BUCKET_ID + " = ? " + AND_PHOTO_FILTER, newString[]{Long.toString(albumId)},
MediaStore.Images.Media.DEFAULT_SORT_ORDER + " ASC");
And as I mentioned, the function might be called multiple times from various threads, so it is definitely possible the same URI is called multiple times for different buckets.
A workaround is to append a query parameter:
MediaStore.Images.Media.EXTERNAL_CONTENT_URI.buildUpon()
.appendQueryParameter("bucket", Long.toString(albumId))
.build()
That way, the query is different for each album, and no CursorLeak error message will be generated.
Post a Comment for "Databaseobjectnotclosedexception Even With Try-with-resources"