学习了一下ContentProvider,照着书上的例子,写了一个小Demo,主要有三个类ContactList.java,PersonInfo.java,DbAccess.java 第一个类是UI界面Activity,第二个类中定义数据库的字段和Uri,第三个类继承自ContentProvider,主要是数据库的操作。
   现在我在ContactList.java添加记录和查询记录,如果直接创建一个DbAccess.java的对象db,然后调用db.insert 和db.query来添加或者查询就会有问题,我看书上的代码,它的查询使用managedQuery,插入是用getContentResolver().insert  ,通过跟踪managedQuery我发现这个方法,最终是要调用DbAccess.java 类中的Query方法的,getContentResolver().insert最终是要调用DbAccess.java中的insert方法的,对于这一点我很不解。
   managedQuery的原理是什么,为什么会调用到DbAccess.java中的query
    getContentResolver这个方法到底是干什么的,为什么getContentResolver().insert会调用DbAccess.java中的insert  ??

解决方案 »

  1.   

    managedQuery是依赖activity的,只不过里面android又包了一些查询方法而已。
    getContentResolver也是一样的,获取cursor后最终修改查询的那些方法都是基本的数据库操作的方法,就是封装了一下,联系人有自己的数据库文件,你当然可以自己去打开那个联系人的数据库文件,然后实现修改等操作,但是这样可能是不安全的,android又包了一些接口,自然有它的道理,应该是做了一些优化和异常的处理吧。
      

  2.   

    getContentResolver是对其他应用程序暴露数据的类似接口的方法...
      

  3.   

    Making the queryTo query a content provider, you can use either the ContentResolver.query() method or the Activity.managedQuery() method. Both methods take the same set of arguments, and both return a Cursor object. However, managedQuery() causes the activity to manage the life cycle of the Cursor. A managed Cursor handles all of the niceties, such as unloading itself when the activity pauses, and requerying itself when the activity restarts. You can ask an Activity to begin managing an unmanaged Cursor object for you by calling Activity.startManagingCursor(). 
      

  4.   

    重点这句: However, managedQuery() causes the activity to manage the life cycle of the Cursor.  产生的游标的生命周期和当前activity关联,activity销毁,Cursor销毁...
      

  5.   


    正解!managedQuery是同activity,有生命周期。也只有在activity类或者派生类中操作。