gpt4 book ai didi

android - 等待异步任务完成

转载 作者:行者123 更新时间:2023-11-29 21:54:33 24 4
gpt4 key购买 nike

我正在开发我的第一个 Android 应用程序。在其中一个页面上,我需要使用 REST 服务连接到 Drupal 站点,检索一些数据(视频 URL 列表、它们的标题、描述等)并将其显示在列表中。当我点击列表时,我会转到视频的详细信息。

这是我想要继续的方式。1° 从 drupal 站点获取所有数据。2° 当点击列表中的一个项目时,将该视频的详细信息传递给下一个 Activity 。

问题是这样的:在 android 3+ 中连接到互联网时,你不能在主线程上进行,所以我不得不使用 AsyncTask 来获取数据。这行得通,但后来我想将视频保存在 ArrayList 中,然后使用 getVideos() 或 getVideo(index) 函数访问该列表。第一个填充列表,第二个在转到详细信息 Activity 之前检索数据。问题是当我尝试访问视频列表时该列表尚未填充。

从技术上讲,我真的不需要/不想使用 asynctask,但是在主线程上连接到 Internet 会抛出一个错误,指出这不是做事的正确方法。

这是我如何获取视频的简化版本:

    public class VideoDaoImpl {
private List<Video> videos ;

public VideoDaoImpl (){
videos = new ArrayList<Video>();
new VideoTask(...).execute(); //fetch the videos in json format and
//call function onRemoteVideoCallComplete using a handler
//in the onPostExecute() function of the asyncTask
}

public List<Video> getVideos() {
return videos;
}

public Video getVideo(int index){
return videos.get(index);
}

public onRemoteVideoCallComplete(JSONObject json) {
//transform Json into videos and add them to the videos arraylist
}

}

这就是我想要在我的 Activity 中填充视频列表的方式:

    public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_videos_list);
//get all videos (not yet filled since faster than second thread)
List<Video> videos = videoDao.getVideos();
//get a list of all the titles to display as the list
List<String> formattedVideos = VideoHelper.formatVideosList(videos);

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, formattedVideos);

ListView listView = (ListView) findViewById(R.id.videos_list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new VideosListItemClickListener(this));
}

所以问题真的是这个。有没有更好的方法,或者有没有办法等待列表被填满。

最佳答案

我会保持 AsyncTask 不变,但我会考虑使用 onPostExecute()。在 onPostExecute() 内部,我会将您的 Json 转换为视频对象列表,然后从中创建格式化视频列表。然后,您可以调用一个方法,将格式化视频列表传递回您的 Activity,然后 Activity 将设置该列表。

例如在你的异步中:

protected void onPostExecute(Json result) {
//Create list of videos from json
//Create formatted list
//call method in activity to set list e.g activity.setList(formatted List)
}

关于android - 等待异步任务完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13567248/

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