Do Android development often encounter android.database.CursorWindowAllocationException such a mistake; This error is generally caused by the fact that the cursor is not closed, Or because the cursor is not used properly, I have encountered this code before:
Forecastdata situation = null; ................ cursor cursor = mcontext.getcontentresolver (). query (Weather_uri, NULL, NULL, NULL, and null ); try { if (cursor! = NULL && Cursor.movetofirst ()) { ... Cursor.close (); } } catch (Exception e) { e.printstacktrace (); } finally { if (cursor! = null) { cursor.close ();} } return situation;}
At first glance there is no problem, but if cursor cursor = mcontext.getcontentresolver (). Query the error returned here is still likely to cause the program's non-closed cursor, so we changed to standard notation:
Cursor cursor = null;try {cursor = Getcontentresolver (). Query (URI, ...); /1 //dosomething} finally {if (cursor! = NULL) {cursor.close ();//2}}
After this change, running a lot of versions has been no problem. Until one day a colleague found it might be time consuming to query the database. So put the method in the thread to execute, and each time the query will create a thread. I did not think that the above code is wrong again, if you are not aware of the problem of this code, because there is no logical problem with try-finally notation. Since the multithreaded scenario is not considered here, try-finally does not guarantee that the query opens the cursor at dosomething time by another thread calling query. So when a multi-threaded call is encountered, a lock must be added to the cursor opening to the closing time period, which is where the try-finally block is locked.
Here's a quick explanation:
Suppose: Thread A executes to 1 to create a cursor, and then dosomething is more time-consuming ...
Thread B also queries the database, so it creates a cursor at 1, and if AB finishes, it closes the lock and looks fine, but because it is the same object, the AB closed cursor is created by B, so
A the cursor created is not closed!
Android Development Database cursor error android.database.CursorWindowAllocationException