107

Android SDK のドキュメントには、startManagingCursor()メソッドが非推奨であると記載されています。

このメソッドは非推奨です。代わりに、LoaderManager で新しい CursorLoader クラスを使用してください。これは、Android 互換性パッケージを通じて古いプラットフォームでも利用できます。このメソッドにより、アクティビティは、アクティビティのライフサイクルに基づいて、指定された Cursor のライフサイクルを管理できます。つまり、アクティビティが停止すると、指定された Cursor で自動的に activate() が呼び出され、後で再開されると requery() が呼び出されます。アクティビティが破棄されると、管理されているすべての Cursor が自動的に閉じられます。HONEYCOMB 以降をターゲットにしている場合は、代わりに getLoaderManager() を介して利用可能な LoaderManager を使用することを検討してください。

ということで使いたいと思いますCursorLoader。しかし、のコンストラクターで URI が必要な場合、どのようにカスタムCursorAdapterとなしで使用できますか?ContentProviderCursorLoader

4

5 に答える 5

155

コンテンツプロバイダーを必要としない単純な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;
    }
}

AsyncTaskLoaderクラスだけが必要です。Android 3.0以降のもの、または互換性パッケージに付属しているもののいずれか。

またListLoaderと互換性があり、ジェネリックコレクションLoadManagerを取得するために使用されるを作成しました。java.util.List

于 2011-09-14T20:07:09.537 に答える
23

コンテンツ プロバイダーの代わりにデータベース クラスを使用する独自のローダーを作成します。最も簡単な方法は、互換性ライブラリからクラスのソースを取得し、CursorLoaderプロバイダー クエリを独自の db ヘルパー クラスへのクエリに置き換えることです。

于 2011-08-25T02:54:07.350 に答える
14

SimpleCursorLoader は単純なソリューションですが、データが変更されたときのローダーの更新をサポートしていません。CommonsWare には、SQLiteCursorLoader を追加し、データ変更の再クエリをサポートする loaderex ライブラリがあります。

https://github.com/commonsguy/cwac-loaderex

于 2012-06-22T17:58:51.373 に答える
12

3 番目のオプションは、単純にオーバーライドすることですloadInBackground

public class CustomCursorLoader extends CursorLoader {
    private final ForceLoadContentObserver mObserver = new ForceLoadContentObserver();

    @Override
    public Cursor loadInBackground() {
        Cursor cursor = ... // get your cursor from wherever you like

        if (cursor != null) {
            // Ensure the cursor window is filled
            cursor.getCount();
            cursor.registerContentObserver(mObserver);
        }

        return cursor;
    }
};

これにより、データベースが変更されたときのカーソルの再クエリも処理されます。

唯一の注意点: Google は無限の知恵でパッケージを非公開にすることを決定したため、別のオブザーバーを定義する必要があります。クラスを元のパッケージ (または互換パッケージ) と同じパッケージに入れると、実際には元のオブザーバーを使用できます。オブザーバーは非常に軽量なオブジェクトであり、他の場所では使用されていないため、大きな違いはありません。

于 2012-06-28T17:16:57.717 に答える
2

Timo Ohr によって提案された 3 番目のオプションは、Yeung によるコメントとともに、最も単純な答え (オッカムの剃刀) を提供します。以下は、私にとってうまくいく完全なクラスの例です。このクラスの使用には 2 つのルールがあります。

  1. この抽象クラスを拡張し、メソッド getCursor() および getContentUri() を実装します。
  2. 基盤となるデータベースが変更されたとき (たとえば、挿入または削除の後) はいつでも、必ず呼び出してください。

    getContentResolver().notifyChange(myUri, null);
    

    ここで、myUri はメソッド getContentUri() の実装から返されるものと同じです。

使用したクラスのコードは次のとおりです。

package com.example.project;

import android.content.Context;
import android.database.Cursor;
import android.content.CursorLoader;
import android.content.Loader;

public abstract class AbstractCustomCursorLoader extends CursorLoader
  {
    private final Loader.ForceLoadContentObserver mObserver = new Loader.ForceLoadContentObserver();

    public AbstractCustomCursorLoader(Context context)
      {
        super(context);
      }

    @Override
    public Cursor loadInBackground()
      {
        Cursor cursor = getCursor();

        if (cursor != null)
          {
            // Ensure the cursor window is filled
            cursor.getCount();
            cursor.registerContentObserver(mObserver);
          }

        cursor.setNotificationUri(getContext().getContentResolver(), getContentUri());
        return cursor;
      }

    protected abstract Cursor getCursor();
    protected abstract Uri getContentUri();
  }
于 2017-03-04T23:20:36.683 に答える