Android development database Cursor error android. database. cursorrentwallocationexception
Android is often used for android development. database. cursorWindowAllocationException is an error like this. Generally, this error occurs because the cursor is not disabled, or because the Cursor is improperly used:
ForecastData situation = null; ................ Cursor cursor = mContext.getContentResolver().query(WEATHER_URI, null, null, null, null); try { if (cursor != null && cursor.moveToFirst()) { ........... cursor.close(); } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null) { cursor.close(); }}return situation;}
There is no problem at first, But If Cursor cursor = mContext. getContentResolver (). query returns an error that may cause the program to not close Cursor, we should change it to the standard syntax:
Cursor cursor = null;try {cursor = getContentResolver().query(URI, .....);// 1 //dosomething} finally {if (cursor != null) {cursor.close();// 2}}
After this change, it is no problem to run many versions. One day, a colleague found that it was time-consuming to query the database. Therefore, the method is put into the thread for execution, and a thread is created every time a query is made. I didn't think that the above Code was wrong again. If you don't pay attention to it, you won't doubt the problem of this Code, because try-finally writing does not have a logic problem. Because multithreading is not taken into account here, try-finally cannot guarantee that when the query cursor is opened in dosomething, another thread calls query again to open the cursor. Therefore, when a multi-threaded call occurs, you must lock the cursor from being opened to the closing period, that is, the try-finally block is locked.
The following is a brief explanation:
Suppose: thread A executes to 1 to create A Cursor, and then dosomething is time-consuming ........
Thread B queries the database again, so another Cursor is created at 1. If the AB execution is complete, the lock will be closed. It seems that there is no problem, but because it is the same object, so the cursor closed by AB is created by B, so
The Cursor created by A is not closed!