Bil*_*hon 9 sqlite android uri android-contentprovider android-loadermanager
这里说它SimpleCursorAdapter的API级别1构造函数已被弃用,建议使用LoaderManager和CursorLoader.
但是深入研究LoaderManager和CursorLoader使用我发现这个例子里面的内部类扩展了一个ListFragment(我认为是Fragment本身的扩展),我们创建了一个CursorLoader.一切似乎确定,不同的是,其实CursorLoader需要一个Uri作为参数.所以这意味着我需要创建一个ContentProvider访问我的数据库的权限.
我必须承认,为了创建一个简单的ListView来自数据库的项目,我们必须完成所有这些操作才能看起来有点过分.特别是如果我不打算将我的数据库数据提供给其他应用程序,并且内容提供商的主要目的是这样做.
那真的值得吗?
特别是在像我这样的情况下,要获取的内容可能会很小.我认真考虑用旧方式做,你怎么说?
我写了一个不需要内容提供者的简单CursorLoader:
import android.content.Context;
import android.database.Cursor;
import android.support.v4.content.AsyncTaskLoader;
/**
* Used to write apps that run on platforms prior to Android 3.0. When running
* on Android 3.0 or above, this implementation is still used; it does not try
* to switch to the framework's implementation. See the framework SDK
* documentation for a class overview.
*
* This was based on the CursorLoader class
*/
public abstract class SimpleCursorLoader extends AsyncTaskLoader<Cursor> {
private Cursor mCursor;
public SimpleCursorLoader(Context context) {
super(context);
}
/* Runs on a worker thread */
@Override
public abstract Cursor loadInBackground();
/* Runs on the UI thread */
@Override
public void deliverResult(Cursor cursor) {
if (isReset()) {
// An async query came in while the loader is stopped
if (cursor != null) {
cursor.close();
}
return;
}
Cursor oldCursor = mCursor;
mCursor = cursor;
if (isStarted()) {
super.deliverResult(cursor);
}
if (oldCursor != null && oldCursor != cursor && !oldCursor.isClosed()) {
oldCursor.close();
}
}
/**
* Starts an asynchronous load of the contacts list data. When the result is ready the callbacks
* will be called on the UI thread. If a previous load has been completed and is still valid
* the result may be passed to the callbacks immediately.
* <p/>
* Must be called from the UI thread
*/
@Override
protected void onStartLoading() {
if (mCursor != null) {
deliverResult(mCursor);
}
if (takeContentChanged() || mCursor == null) {
forceLoad();
}
}
/**
* Must be called from the UI thread
*/
@Override
protected void onStopLoading() {
// Attempt to cancel the current load task if possible.
cancelLoad();
}
@Override
public void onCanceled(Cursor cursor) {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
@Override
protected void onReset() {
super.onReset();
// Ensure the loader is stopped
onStopLoading();
if (mCursor != null && !mCursor.isClosed()) {
mCursor.close();
}
mCursor = null;
}
}
Run Code Online (Sandbox Code Playgroud)
它只需要AsyncTaskLoader上课.Android 3.0或更高版本中的一个,或兼容包附带的那个.
| 归档时间: |
|
| 查看次数: |
8804 次 |
| 最近记录: |