简体   繁体   English

我的onResume依赖于`onViewCreated`。 我该如何重新设计呢?

[英]My onResume depends on `onViewCreated`. How can I redesign it?

I have a fragment and onViewCreated an AsyncTask is started that loads some data in the background and in onPostExecute it loads the data to an ArrayAdapter to be displayed to a list in the UI. 我有一个片段和onViewCreated ,启动AsyncTask,在后台加载一些数据,在onPostExecute它将数据加载到ArrayAdapter ,以显示在UI中的列表中。
Now onResume I need to load some other data that needs to be loaded in a background thread. 现在onResume我需要加载一些需要在后台线程中加载的其他数据。 So I can use start an AsyncTask for that. 所以我可以使用启动AsyncTask。
This second background task loads some other data from another data source. 第二个后台任务从另一个数据源加载一些其他数据。

Problem: Once these data are loaded and before finishing process I need to do access the data loaded in the ArrayAdapter from the AsyncTask of onViewCreated . 问题:加载这些数据后,在完成处理之前,我需要从onViewCreatedAsyncTask访问ArrayAdapter加载的数据。
Taking into account that: 考虑到:
1) I should not access the ArrayAdapter from a non-UI thread and 1)我不应该从非UI线程访问ArrayAdapter
2) I can't be sure that the AsyncTask of onViewCreated has already been finished (I recently was informed that AsyncTasks are actually run one after the other) 2)我无法确定onViewCreatedAsyncTask是否已经完成(我最近被告知AsyncTasks实际上是一个接一个地运行)
How can I fix my design so that this works? 如何修复我的设计以使其有效?
Please note that the data loaded onViewCreated are much much more than the data loaded onResume so preferably I would not want to reload them on each resume 请注意,加载onViewCreated的数据远远多于onResume加载的数据,所以我不希望在每个简历上重新加载它们

You can check the status of your AsyncTask with a call to .getStatus() and see if it's ie finished ( AsyncTask.Status.FINISHED ). 您可以通过调用.getStatus()来检查AsyncTask的状态,看看它是否已完成( AsyncTask.Status.FINISHED )。 As for accessing the adapter from inside the asyncTask, you need to use onProgressUpdate , which is triggered on every update of the task, or in case you don't update the progress, it can be wrapped inside a Runnable like so: 至于从asyncTask内部访问适配器,您需要使用onProgressUpdate ,它在每次更新任务时触发,或者如果您不更新进度,它可以包装在Runnable如下所示:

//Inside doInBackground
runOnUiThread(new Runnable() {
    public void run() {
        //Your logic
    }
});

The difference is that if your code is something like downloading an image, or a file, that will be run inside a loop, reading n bytes everytime. 不同之处在于,如果您的代码类似于下载图像或文件,那么它将在循环内运行,每次读取n个字节。 You can call publishProgress(Progress...) to trigger the onProgressUpdate method and show feedback to the user, as in 50% downloaded. 您可以调用publishProgress(Progress...)来触发onProgressUpdate方法并向用户显示反馈,如下载50%。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM