android之Activity.startManagingCursor方法详解

来源:互联网 发布:网络一线牵老年表情 编辑:程序博客网 时间:2024/06/05 11:40

在使用数据库操作查询数据后,如果是在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 callCursor.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 usingLoaderManager instead, available viagetLoaderManager().

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

 
看不懂没关系,下面三条懂了就行:
1.这个方法使用的前提是:游标结果集里有数据记录。
所以,在使用之前,先对Cursor是否为null进行判断,如果Cursor != null,再使用此方法
 
2.如果使用这个方法,最后也要用stopManagingCursor()来把它停止掉,以免出现错误。
 
3.使用这个方法的目的是把获取的Cursor对象交给Activity管理,这样Cursor的生命周期便能和Activity自动同步,
省去自己手动管理。如果不调用,那么工作就要你自己来做,在Activity被stopped时,调用Cursor.deactivate,在restart的时候调用Cursor.requery,还有其他状态也最好都与Activity保持同步,以免出现一些错误,不过,为什么不用现成的startManagingCursor,省时又省力.
原创粉丝点击