您的位置:首页 > 移动开发 > Android开发

android中Activity.startManagingCursor(cursor)方法详解

2015-08-09 14:00 519 查看
在使用数据库操作查询数据后,如果是在Activity里面处理,那么很可能就会用到startManagingCursor()方法,

startManagingCursor()作用和使用注意事项:

调用这个方法,就是将获得的Cursor对象交与Activity 来管理,这样Cursor对象的生命周期便能与当前的Activity自动同步,省去了自己管理Cursor。

看API中的注释

This method allows the activity to take care of managing the given
Cursor
's
lifecycle for you based on the activity's lifecycle. That is, when the activity is stopped it will automatically call
Cursor.deactivate
on
the given Cursor, and when it is later restarted it will call
Cursor.requery
for
you. When the activity is destroyed, all managed Cursors will be closed automatically. If you are targeting
android.os.Build.VERSION_CODES.HONEYCOMB
or
later, consider instead using
LoaderManager
instead,
available via
getLoaderManager()
.

Warning: Do not call
Cursor.close()
on
cursor obtained from
managedQuery
, because the activity
will do that for you at the appropriate time. However, if you call
stopManagingCursor
on
a cursor from a managed query, the system will not automatically close the cursor and, in that case, you must call
Cursor.close()
.

记住以下三条:

1.这个方法使用的前提是:游标结果集里有数据记录。

所以,在使用之前,先对Cursor是否为null进行判断,如果Cursor != null,再使用此方法

2.如果使用这个方法,最后也要用stopManagingCursor()来把它停止掉,以免出现错误。

3.使用这个方法的目的是把获取的Cursor对象交给Activity管理,这样Cursor的生命周期便能和Activity自动同步,省去自己手动管理。如果不调用,那么很多工作就要你自己来做,在Activity被stopped时,调用Cursor.deactivate,在restart的时候调用Cursor.requery,还有其他状态也最好都与Activity保持同步,以免出现一些错误,不过,为什么不用现成的startManagingCursor,省时又省力.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: