什么是在Android 2.2中使用游标适配器和内容提供程序的正确方法

时间:2011-10-02 13:48:31

标签: android android-contentprovider simplecursoradapter android-cursoradapter android-loadermanager

我很困惑,我需要你的帮助。 我尝试按照Virgil Dobjanschi在Google IO 2010上给出的演讲“Developing Android REST Client Applications”上的说明。不幸的是,我找不到在Content Provider和Cursor Adapter之间实现有效通信的方法。

我在这里遇到的问题是与游标适配器相关联,所以让我们假设内容提供商的一切都很好。例如,让我们尝试使用Contacts ContentProvider而不是我自己的。我尝试了最简单的解决方案 - 任何ContentProvider(假定为SDK,由SDK提供)和SimpleCursorAdapter。问题是不推荐使用包含来自Contacts的游标的SimpleCursorAdapter的构造函数。文件说:

  

不推荐使用此构造函数。

     

不鼓励使用此选项,因为它会导致在应用程序的UI线程上执行Cursor查询,从而导致响应能力较差甚至应用程序无响应错误。或者,使用带有CursorLoader的LoaderManager。

我的想法是:“好的,我不会使用它。我会尝试使用CursorLoader加载LoaderManager,因为他们建议我。”所以我去LoaderManager documentation site寻找一个使用的例子和我发现的东西?使用SimpleCursorAdapter构造函数的完美示例。是的,同样我想避免因为它的弃用。

    // Create an empty adapter we will use to display the loaded data.
    mAdapter = new SimpleCursorAdapter(getActivity(),
            android.R.layout.simple_list_item_2, null,
            new String[] { Contacts.DISPLAY_NAME, Contacts.CONTACT_STATUS },
            new int[] { android.R.id.text1, android.R.id.text2 }, 0);
    setListAdapter(mAdapter);

我能找到的所有教程都使用了这个不推荐使用的构造函数。任何人都可以给我很好的答案,避免使用它的方法是什么?或者也许我太关心了?我想要的只是学习良好实践......

1 个答案:

答案 0 :(得分:1)

如果您在Android 2.2上使用LoaderManager,那么您已经在项目中使用了Android兼容性库。

在这种情况下,请勿使用

android.widget.SimpleCursorAdapter

因为该类只有一个现在已弃用的构造函数。而是使用:

android.support.v4.widget.SimpleCursorAdapter
来自compat库的

。它有两个构造函数:

SimpleCursorAdapter(Context, int, Cursor, String[], int[]) // deprecated
SimpleCursorAdapter(Context, int, Cursor, String[], int[], int) // non-deprecated

您问题中的代码示例使用第二个不推荐使用的构造函数,因此必须使用SimpleCursorAdapter的compat lib版本。