public class

CursorLoader

extends AsyncTaskLoader<Cursor>

 java.lang.Object

androidx.loader.content.Loader<java.lang.Object>

androidx.loader.content.AsyncTaskLoader<Cursor>

↳androidx.loader.content.CursorLoader

Gradle dependencies

compile group: 'androidx.loader', name: 'loader', version: '1.1.0'

  • groupId: androidx.loader
  • artifactId: loader
  • version: 1.1.0

Artifact androidx.loader:loader:1.1.0 it located at Google repository (https://maven.google.com/)

Androidx artifact mapping:

androidx.loader:loader com.android.support:loader

Androidx class mapping:

androidx.loader.content.CursorLoader android.support.v4.content.CursorLoader

Overview

Static library support version of the framework's . 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.

Summary

Constructors
publicCursorLoader(Context context)

Creates an empty unspecified CursorLoader.

publicCursorLoader(Context context, Uri uri, java.lang.String projection[], java.lang.String selection, java.lang.String selectionArgs[], java.lang.String sortOrder)

Creates a fully-specified CursorLoader.

Methods
public voidcancelLoadInBackground()

Called on the main thread to abort a load in progress.

public voiddeliverResult(java.lang.Object data)

Sends the result of the load to the registered listener.

public voiddump(java.lang.String prefix, java.io.FileDescriptor fd, java.io.PrintWriter writer, java.lang.String args[])

public java.lang.StringgetProjection()

public java.lang.StringgetSelection()

public java.lang.StringgetSelectionArgs()

public java.lang.StringgetSortOrder()

public UrigetUri()

public abstract java.lang.ObjectloadInBackground()

Called on a worker thread to perform the actual load and to return the result of the load operation.

public voidonCanceled(java.lang.Object data)

Called if the task was canceled before it was completed.

protected voidonReset()

Subclasses must implement this to take care of resetting their loader, as per Loader.reset().

protected voidonStartLoading()

Starts an asynchronous load of the contacts list data.

protected voidonStopLoading()

Must be called from the UI thread

public voidsetProjection(java.lang.String projection[])

public voidsetSelection(java.lang.String selection)

public voidsetSelectionArgs(java.lang.String selectionArgs[])

public voidsetSortOrder(java.lang.String sortOrder)

public voidsetUri(Uri uri)

from AsyncTaskLoader<D>getExecutor, isLoadInBackgroundCanceled, onCancelLoad, onForceLoad, onLoadInBackground, setUpdateThrottle
from Loader<D>abandon, cancelLoad, commitContentChanged, dataToString, deliverCancellation, forceLoad, getContext, getId, isAbandoned, isReset, isStarted, onAbandon, onContentChanged, registerListener, registerOnLoadCanceledListener, reset, rollbackContentChanged, startLoading, stopLoading, takeContentChanged, toString, unregisterListener, unregisterOnLoadCanceledListener
from java.lang.Objectclone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructors

public CursorLoader(Context context)

Creates an empty unspecified CursorLoader. You must follow this with calls to CursorLoader.setUri(Uri), CursorLoader.setSelection(String), etc to specify the query to perform.

public CursorLoader(Context context, Uri uri, java.lang.String projection[], java.lang.String selection, java.lang.String selectionArgs[], java.lang.String sortOrder)

Creates a fully-specified CursorLoader. See for documentation on the meaning of the parameters. These will be passed as-is to that call.

Methods

public abstract java.lang.Object loadInBackground()

Called on a worker thread to perform the actual load and to return the result of the load operation. Implementations should not deliver the result directly, but should return them from this method, which will eventually end up calling Loader.deliverResult(D) on the UI thread. If implementations need to process the results on the UI thread they may override Loader.deliverResult(D) and do so there. To support cancellation, this method should periodically check the value of AsyncTaskLoader.isLoadInBackgroundCanceled() and terminate when it returns true. Subclasses may also override AsyncTaskLoader.cancelLoadInBackground() to interrupt the load directly instead of polling AsyncTaskLoader.isLoadInBackgroundCanceled(). When the load is canceled, this method may either return normally or throw OperationCanceledException. In either case, the Loader will call AsyncTaskLoader.onCanceled(D) to perform post-cancellation cleanup and to dispose of the result object, if any.

Returns:

The result of the load operation.

See also: AsyncTaskLoader.isLoadInBackgroundCanceled(), AsyncTaskLoader.cancelLoadInBackground(), AsyncTaskLoader.onCanceled(D)

public void cancelLoadInBackground()

Called on the main thread to abort a load in progress. Override this method to abort the current invocation of AsyncTaskLoader.loadInBackground() that is running in the background on a worker thread. This method should do nothing if AsyncTaskLoader.loadInBackground() has not started running or if it has already finished.

See also: AsyncTaskLoader.loadInBackground()

public void deliverResult(java.lang.Object data)

Sends the result of the load to the registered listener. Should only be called by subclasses. Must be called from the process's main thread.

Parameters:

data: the result of the load

protected void onStartLoading()

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

protected void onStopLoading()

Must be called from the UI thread

public void onCanceled(java.lang.Object data)

Called if the task was canceled before it was completed. Gives the class a chance to clean up post-cancellation and to properly dispose of the result.

Parameters:

data: The value that was returned by AsyncTaskLoader.loadInBackground(), or null if the task threw OperationCanceledException.

protected void onReset()

Subclasses must implement this to take care of resetting their loader, as per Loader.reset(). This is not called by clients directly, but as a result of a call to Loader.reset(). This will always be called from the process's main thread.

public Uri getUri()

public void setUri(Uri uri)

public java.lang.String getProjection()

public void setProjection(java.lang.String projection[])

public java.lang.String getSelection()

public void setSelection(java.lang.String selection)

public java.lang.String getSelectionArgs()

public void setSelectionArgs(java.lang.String selectionArgs[])

public java.lang.String getSortOrder()

public void setSortOrder(java.lang.String sortOrder)

public void dump(java.lang.String prefix, java.io.FileDescriptor fd, java.io.PrintWriter writer, java.lang.String args[])

Deprecated: Consider using LoaderManager.enableDebugLogging(boolean) to understand the series of operations performed by LoaderManager.

Source

/*
 * Copyright 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package androidx.loader.content;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContentResolverCompat;
import androidx.core.os.CancellationSignal;
import androidx.core.os.OperationCanceledException;
import androidx.loader.app.LoaderManager;

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

/**
 * Static library support version of the framework's {@link android.content.CursorLoader}.
 * 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.
 */
public class CursorLoader extends AsyncTaskLoader<Cursor> {
    private final ForceLoadContentObserver mObserver;

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

    private Cursor mCursor;
    private CancellationSignal mCancellationSignal;

    /* Runs on a worker thread */
    @Override
    public Cursor loadInBackground() {
        synchronized (this) {
            if (isLoadInBackgroundCanceled()) {
                throw new OperationCanceledException();
            }
            mCancellationSignal = new 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();
                    cursor.registerContentObserver(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 CursorLoader(@NonNull Context context) {
        super(context);
        mObserver = new 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 CursorLoader(@NonNull Context context, @NonNull Uri uri, @Nullable String[] projection,
            @Nullable String selection, @Nullable String[] selectionArgs,
            @Nullable String sortOrder) {
        super(context);
        mObserver = new 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;
    }

    @NonNull
    public Uri getUri() {
        return mUri;
    }

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

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

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

    @Nullable
    public String getSelection() {
        return mSelection;
    }

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

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

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

    @Nullable
    public String getSortOrder() {
        return mSortOrder;
    }

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

    /**
     * @deprecated Consider using {@link LoaderManager#enableDebugLogging(boolean)} to understand
     * the series of operations performed by LoaderManager.
     */
    @SuppressWarnings("deprecation")
    @Override
    @Deprecated
    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);
    }
}