gpt4 book ai didi

android - AsyncTaskLoader 不会调用 onLoadFinished 除非我在 loadInBackground 中返回一个新对象

转载 作者:太空宇宙 更新时间:2023-11-03 12:19:51 26 4
gpt4 key购买 nike

我有一个 AsyncTaskLoader<List<String>>带有成员变量 List<String> m地址。在 loadInBackground ,如果我创建一个新对象,填充它,然后返回它; onLoadFinished按预期调用,因此我可以更新适配器,进而更新 View 。

    public List<String> loadInBackground()
{
// ListView updates properly only if I do this (strange?)
mAddresses = new ArrayList<String>();

// ... fill mAddresses ...

return mAddresses;
}

但是,如果我尝试使用同一个变量,即使它的值发生变化onLoadFinished确实被调用:

    public List<String> loadInBackground()
{
// ListView does not update with this!
if(mAddresses == null)
{
mAddresses = new ArrayList<String>();
}

// ... fill mAddresses ...

return mAddresses;
}

任何人都可以对此发表评论吗?我是否应该像这样每次都创建一个新对象来返回?是否有任何我可以设置的标志表明“对象已更改,因此即使它是同一个对象,也要确保执行所有更新?

最佳答案

如果数据已经加载(就像加载程序中的“mAddresses”变量中显示的那样),您需要调用 forceLoad() 以使其再次加载:

http://developer.android.com/reference/android/content/Loader.html#forceLoad%28%29



编辑:...经过一番调查...毫无帮助地回答您最初的问题:“因为它没有”!

来自 LoaderManager 的源代码:

        // Notify of the new data so the app can switch out the old data before
// we try to destroy it.
if (mData != data || !mHaveData) {
mData = data;
mHaveData = true;
if (mStarted) {
callOnLoadFinished(loader, data);
}
}

http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.3_r2.1/android/app/LoaderManager.java#LoaderManagerImpl.LoaderInfo.onLoadComplete%28android.content.Loader%2Cjava.lang.Object%29

关于您的问题,我假设您不断地向 loadInBackground() 中的列表添加内容,而不是清除并重新开始。最干净的方法是每次通过将现有列表作为参数传递给 ArrayList() 构造函数来构建一个新的 ArrayList,它将复制内容。
或者你可以覆盖 deliverResult(),它是从主线程调用的,所以修改 mAdapter 是可以的。
或者忘记 Loader,只使用更简单的 AsyncTask...尽管这取决于您的数据实际来自何处。

关于android - AsyncTaskLoader 不会调用 onLoadFinished 除非我在 loadInBackground 中返回一个新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18982467/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com