android之Activity.startManagingCursor方法详解

在使用数据库操作查询数据后,如果是在Activity里面处理,那么很可能就会用到startManagingCursor()方法,在这里讲一下它的作用和使用注意事项.调用这个方法,就是将获得的Cursor对象交与Activity 来管理,这样Cursor对象的生命周期便能与当前的Activity自动同步,省去了自己管理Cursor。看下文档里的注释This method allows

大家好,又见面了,我是全栈君。

在使用数据库操作查询数据后,如果是在Activity里面处理,那么很可能就会用到startManagingCursor()方法,在这里讲一下它的作用和使用注意事项.

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

看下文档里的注释

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,省时又省力.
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/121427.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号