Android:在使用CursorLoader时,防止在ContentProvider中忘记父/后代uri?

时间:2015-11-28 06:17:50

标签: uri parent-child android-contentprovider notify android-cursorloader

我有一个var gamebuttonslist=document.querySelectorAll("#gamebuttons button"); for (var vitem=0;vitem<gamebuttonslist.length;vitem++) { if (typeof gamebuttonslist[vitem] != "undefined" && gamebuttonslist[vitem] != null) { gamebuttonslist[vitem].style.cursor = "pointer"; gamebuttonslist[vitem].addEventListener("click", clickHandler, false); gamebuttonslist[vitem].addEventListener("mousedown", mousedownHandler, false); gamebuttonslist[vitem].addEventListener("mouseout", mouseoutHandler, false); } } ,可以使用此CursorLoader观察目录:

URI

以及使用此uriDirectory = content://com.myapp.stocks/stocks观察项目的另一个CursorLoader

URI

当我更新uriItem = content://com.myapp.stocks/stocks/GOOG并在uriItem中致电getContext().getContentResolver().notifyChange(uriItem , null);时,如何阻止它同时通知ContentProvider

谢谢!

修改:所以到目前为止我的解决方案只是在我通知uriDirectory时将boolean设置为true。然后,当它通知父项uriItem时,它将看到布尔值为true并且不会执行任何操作。之后,我将uriDirectory设置回boolean

1 个答案:

答案 0 :(得分:0)

您可以自己编写CursorLoader。默认光标加载器通过Cursor.RegisterContentObserver(ContentObserver observer)注册内容观察者。相反,我们想要使用registerContentObserver(Uri uri, boolean notifyForDescendants, ContentObserver observer)

我不确定您是否使用支持库loadInBackground(),但为了最大的适用性,这就是我正在使用的。

库存Android版本的唯一变化是loadInBackground。您应该创建一个完整的类,而不是仅仅扩展android&#39;并覆盖ContentProvider,因为它可以保护您免受未来对Android的更改。请注意,除非您的设备是KitKat或更新版

,否则不会使用您为Uri notificationUri; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { notificationUri = cursor.getNotificationUri(); } else { notificationUri = mUri; } getContext().getContentResolver().registerContentObserver( notificationUri != null ? notificationUri : mUri, false, //don't notify for descendants mObserver ); 中的光标设置的任何通知网址
package com.innomatixdata.busscan.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.ContentResolverCompat;
import android.support.v4.content.Loader;

import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.Arrays;

public class DescendantChangeIgnoringCursorLoader extends AsyncTaskLoader<Cursor> {
    final Loader.ForceLoadContentObserver mObserver;

    Uri mUri;
    String[] mProjection;
    String mSelection;
    String[] mSelectionArgs;
    String mSortOrder;

    Cursor mCursor;
    android.support.v4.os.CancellationSignal mCancellationSignal;

    /* Runs on a worker thread */
    @Override
    public Cursor loadInBackground() {
        synchronized (this) {
            if (isLoadInBackgroundCanceled()) {
                throw new android.support.v4.os.OperationCanceledException();
            }
            mCancellationSignal = new android.support.v4.os.CancellationSignal();
        }
        try {
            Cursor cursor = ContentResolverCompat.query(getContext().getContentResolver(),
                    mUri, mProjection, mSelection, mSelectionArgs, mSortOrder,
                    mCancellationSignal);
            if (cursor != null) {
                try {
                    // Ensure the cursor window is filled.
                    cursor.getCount();
                    Uri notificationUri;
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                        notificationUri = cursor.getNotificationUri();
                    } else {
                        notificationUri = mUri;
                    }
                    getContext().getContentResolver().registerContentObserver(
                            notificationUri != null ? notificationUri : mUri,
                            false, //don't notify for descendants
                            mObserver
                    );
                } catch (RuntimeException ex) {
                    cursor.close();
                    throw ex;
                }
            }
            return cursor;
        } finally {
            synchronized (this) {
                mCancellationSignal = null;
            }
        }
    }

    @Override
    public void cancelLoadInBackground() {
        super.cancelLoadInBackground();

        synchronized (this) {
            if (mCancellationSignal != null) {
                mCancellationSignal.cancel();
            }
        }
    }

    /* 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();
        }
    }

    /**
     * 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 DescendantChangeIgnoringCursorLoader(Context context) {
        super(context);
        mObserver = new Loader.ForceLoadContentObserver();
    }

    /**
     * Creates a fully-specified CursorLoader.  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 DescendantChangeIgnoringCursorLoader(Context context, Uri uri, String[] projection, String selection,
                                                String[] selectionArgs, String sortOrder) {
        super(context);
        mObserver = new Loader.ForceLoadContentObserver();
        mUri = uri;
        mProjection = projection;
        mSelection = selection;
        mSelectionArgs = selectionArgs;
        mSortOrder = sortOrder;
    }

    /**
     * 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() {
        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;
    }

    public Uri getUri() {
        return mUri;
    }

    public void setUri(Uri uri) {
        mUri = uri;
    }

    public String[] getProjection() {
        return mProjection;
    }

    public void setProjection(String[] projection) {
        mProjection = projection;
    }

    public String getSelection() {
        return mSelection;
    }

    public void setSelection(String selection) {
        mSelection = selection;
    }

    public String[] getSelectionArgs() {
        return mSelectionArgs;
    }

    public void setSelectionArgs(String[] selectionArgs) {
        mSelectionArgs = selectionArgs;
    }

    public String getSortOrder() {
        return mSortOrder;
    }

    public void setSortOrder(String sortOrder) {
        mSortOrder = sortOrder;
    }

    @Override
    public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
        super.dump(prefix, fd, writer, args);
        writer.print(prefix); writer.print("mUri="); writer.println(mUri);
        writer.print(prefix); writer.print("mProjection=");
        writer.println(Arrays.toString(mProjection));
        writer.print(prefix); writer.print("mSelection="); writer.println(mSelection);
        writer.print(prefix); writer.print("mSelectionArgs=");
        writer.println(Arrays.toString(mSelectionArgs));
        writer.print(prefix); writer.print("mSortOrder="); writer.println(mSortOrder);
        writer.print(prefix); writer.print("mCursor="); writer.println(mCursor);
    }
}

Full class descendantChangeIgnoringCursorLoader.java:

$(window).trigger('resize');