14

我正在使用一个AsyncTaskLoader. 我有一个已经实现的活动LoaderCallbacks(支持库)。

我已调试断点并放入日志,加载程序提供结果,但是第二次onLoadFinished未触发回调。奇怪的是 - 当我再次旋转时它起作用了,当我回到它时,我开始的任何方向都会得到回调。

在我的活动中onResume

LoaderManager lm = getSupportLoaderManager();
Loader loader = lm.initLoader(0, null, new LoaderManager.LoaderCallbacks<String>() {

        @Override
        public Loader<String> onCreateLoader(int i, Bundle bundle) {
            Loader<String> loader = new TestLoader(MainActivity.this);
            return loader;
        }

        @Override
        public void onLoadFinished(Loader<String> stringLoader, String s) {
            Log.d(Application.TAG, "OnLoadFinished " + s);
            doStuff(s);
        }

        @Override
        public void onLoaderReset(Loader<String> stringLoader) {
            // NOP
        }
    });

在我的装载机中:

public class TestLoader extends AsyncTaskLoader<String> {
    private String mData;

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

    // This get's called after a loader is initialized or a loader 
    // that is alive still is reset
    @Override
    public void onStartLoading() {
        if (mData != null) { // Have our data loaded, just deliver it!
            deliverResult(mData);
        }
        if (takeContentChanged() || mData == null) {
            forceLoad();
        }
    }

    // This is called when an Activity or Fragment requests a loader 
    // to be reset because they want new data
    @Override
    public void onReset() {
        mData = null;
        // Ensure that the old task is cancelled if it was running
        // We do NOT have to call forceLoad here because onStartLoading 
        // will get called after this
        cancelLoad();
    }

    // Here we just want to store our own data we got and reset our boolean
    @Override
    public void deliverResult(String data) {
        Log.d(Application.TAG, "deliverResult " + data);
        mData = data;
        super.deliverResult(mData);
    }

    @Override
    public String loadInBackground() {
       // returns content from a content provider ... 
    }
}

对此真的感到困惑,我是Android新手,所以也许这对其他人来说很明显:)

4

2 回答 2

25

如果它是一个或如果它是一个,你至少必须简单地调用getSupportLoaderManager()/ getLoaderManager()。实际可以在其他地方。否则加载器将处于停止状态,即使完成加载也不会传递结果。我怀疑这是因为加载器管理器不会将旧加载器重新附加到新加载器,除非在 new中进行上述调用。onCreate()ActivityonActivityCreated()FragmentinitLoader()ActivityActivityonCreate()

于 2014-01-24T09:08:24.917 回答
1

你有

Loader loader = lm.initLoader(...)

你应该有

Loader loader = new LoaderManager.LoaderCallbacks(...) {...}

在你的onResume()

this.getLoaderManager().restartLoader(0, null, this.loader);

请参阅加载程序文档

于 2013-04-13T14:38:40.350 回答