做android 开发的经常会遇android.database.CursorWindowAllocationException这样子的错误;一般出现这样的错误,大部分原因是因为没有关闭cursor,或者是因为Cursor使用不当,之前我的遇到这样的代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
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;
}
|
1
2
3
4
5
6
7
8
9
|
Cursor cursor =
null
;
try
{
cursor = getContentResolver().query(URI, .....);
// 1
//dosomething
}
finally
{
if
(cursor !=
null
) {
cursor.close();
// 2
}
}
|
下面简单解释一下:
假设:线程A执行到1处创建了一个Cursor,然后dosomething比较耗时……..
线程B又来查询数据库,因此到1处又创建一个Cursor,此时如果AB执行完,就会关闭锁,看起来没有问题,但由于是同一个对象,所以AB关闭的cursor都是B创建的,因此
A创建的Cursor就没有关闭!