android - 加载程序在源数据更改时不加载数据

标签 android android-fragments simplecursoradapter android-cursoradapter

Android 文档指出 LOADERS - 它们监视数据源并在内容更改时提供新结果。我已将 CursorAdapter 更改为适用于 SQLite 数据库。

import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader.ForceLoadContentObserver;
import android.util.Log;


public class SimpleCursorLoader extends AsyncTaskLoader<Cursor> {

final ForceLoadContentObserver mObserver;

String mTable;
String[] mColumns;
String mSelection;
String[] mSelectionArgs;
String mGroupBy;
String mHaving;
String mOrderBy;
String mLimit;

Cursor mCursor;
SQLiteDatabase mDb;
 /**
 * Creates an empty unspecified CursorLoader.  You must follow this with
 * calls to {@link #setUri(Uri)}, {@link #setSelection(String)}, etc
 * to specify the query to perform.
 */
public SimpleCursorLoader(Context context) {
    super(context);
    mObserver = new ForceLoadContentObserver();
}

/**
 * Creates a fully-specified SimpleCursorLoader.  See
 * {@link ContentResolver#query(Uri, String[], String, String[], String)
 * ContentResolver.query()} for documentation on the meaning of the
 * parameters.  These will be passed as-is to that call.
 */
public SimpleCursorLoader(Context context,String table, String[] columns, String      selection, 
        String[] selectionArgs, String groupBy, String having, String orderBy, String limit, SQLiteDatabase db) {

    super(context);
    mObserver = new ForceLoadContentObserver();
    mTable = table;
    mColumns = columns; //copying array
    mSelection = selection;
    mSelectionArgs = selectionArgs;
    mGroupBy = groupBy;
    mHaving = having;
    mOrderBy =  orderBy;
    mLimit = limit;
    mDb = db;
}       

    /* Runs on a worker thread */
@Override
public Cursor loadInBackground() {
    Cursor cursor = mDb.query(mTable, mColumns, mSelection, mSelectionArgs, mGroupBy, mHaving, mOrderBy, mLimit);
    if (cursor != null) {
        // Ensure the cursor window is filled
        cursor.getCount();
        Log.d("SimpleCursorLoader","Cursor.getCount()= " + String.valueOf(cursor.getCount()));
        registerContentObserver(cursor, mObserver);
    }
    return cursor;
}

/**
 * Registers an observer to get notifications from the content provider
 * when the cursor needs to be refreshed.
 */
void registerContentObserver(Cursor cursor, ContentObserver observer) {
    cursor.registerContentObserver(mObserver);
}

/* Runs on the UI thread */
@Override
public void deliverResult(Cursor cursor) {
    Log.d("Gaurav","Inside SimpleCursorLoader - deliverResult");
    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.
 *
 * Must be called from the UI thread
 */
@Override
protected void onStartLoading() {
    Log.d("Gaurav", "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;
}

}

CursorLoader 在带有自定义适配器的 ListFragment 中工作,该适配器扩展了 SimpleCursor 适配器并在构造函数中传递了 FLAG_REGISTER_CONTENT_OBSERVER,但是当基础数据被列表中使用的响应更改时,游标会发生变化。

最佳答案

虽然我使用的实现方式与您不同,但我遇到了同样的问题。通过将通知 URI 明确声明为不太具体的内容,我能够更正我的问题。我确定我的代码还有其他问题导致我需要这样做,但它解决了我的问题。因此,我的内容提供程序中的 Cursor 查询来自:

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,  String sortOrder) {

................
................
................

Cursor cursor = queryBuilder.query(mDB.getReadableDatabase(),
                projection, selection, selectionArgs, null, null, sortOrder);
                cursor.setNotificationUri(getContext().getContentResolver(), uri);
cursor.setNotificationUri(getContext().getContentResolver(), uri;)

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,  String sortOrder) {

................
................
................

Cursor cursor = queryBuilder.query(mDB.getReadableDatabase(),
                projection, selection, selectionArgs, null, null, sortOrder);
                cursor.setNotificationUri(getContext().getContentResolver(), uri);
cursor.setNotificationUri(getContext().getContentResolver(), MYURI;)

其中 MYURI 是我知道的 URI 类型的变量,它将涵盖我正在观看的所有内容。

希望这对某人有所帮助。

关于android - 加载程序在源数据更改时不加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7652487/

相关文章:

android - 无法解决Android Studio中Gradle中的第三方库依赖关系

android - 中断当前的 TalkBack 读出并开始新的读出?

android - 在 ViewPager 中输入动画

android - 在 fragment 中使用 Context 和 getactivity 之间的区别?

Android;如何通过游标填充 ListView

android - 在 ListView 中选择多个项目

android - 如何使用 simplecursoradapter 按 id 在特定项目上定位(选择)微调器?

c# - 在 xamarin listview w 上更改选定的颜色

java - android java setOnClickListener 错误

java - 从 fragment 到上一个主页 fragment 的后退按钮箭头