我有一个 Android 应用程序,其中有一个登录系统和一些其他与服务器通信的东西。有时我只是从网络服务器得到一个确认,有时我得到很多数据。到目前为止我使用的是一个简单的数据库。今天我实现了一个到目前为止正在运行的内容提供程序。为了从 ContentProvider 获取数据,我使用了这个 Cursor cursor = getContentResolver().query();
,但我看到还有使用 CursorLoader 的选项。它们之间有什么区别?就我而言,我应该使用什么?我还看到我必须在每个类中实现它cursorLoader,我不能为它创建一个类并在需要时调用它吗?
最佳答案
作为documentation州,
CursorLoader implements the Loader protocol in a standard way for querying cursors, building on AsyncTaskLoader to perform the cursor query on a background thread so that it does not block the application's UI.
这是使用Loaders的最大优点,即它是异步的。还提到了其他一些重要优点here .
- They provide asynchronous loading of data.
- They monitor the source of their data and deliver new results when the content changes.
- They automatically reconnect to the last loader's cursor when being recreated after a configuration change. Thus, they don't need to re-query their data.
如果您通过直接查询内容提供程序来使用默认游标,那么您需要处理关闭它们,并且正如您所说,您有大量数据,您必须在不同的线程上运行查询代码。对于所有这些目的,使用 CursorLoaders 更加简单和高效。有关如何使用的代码,请查看 this出来。
关于你的第二个问题,
I also saw that I have to implement it in every class the cursorLoader, can't I make a single class for it and call it when it's needed ?
您可以很好地创建一个将实现加载器回调的基类,然后您可以从所有需要使用 CursorLoaders 的类继承该基类。
关于android - 我应该使用 Cursor 还是 CursorLoader?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30607842/