gpt4 book ai didi

java - 安卓开发 : How do I integrate threads in this?

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

所以我正在尝试通过从 youtube channel 检索 json 数据来制作一个 youtube 应用程序。问题是我很擅长编写单线程应用程序。但是当涉及到多线程时,我总是失去洞察力。

我还没有在学校学过,大多数教程都是垃圾,或者至少我发现了这一点。

所以我想做的是在我的“GetVideos”类中引入一个线程,这样它就不会在检索视频时减慢我的应用程序。我知道我必须使用处理程序和线程,但每次我尝试使用它们时,我的应用程序都会崩溃。你们能帮忙吗?

public class GetVideos { //class that retrieves JSON data based on youtube username

private String channelName;
private HttpClient client; //client that gets info
private VideoLibrary lib;


public GetVideos(String channelName) {
this.channelName = channelName;
client = new DefaultHttpClient();
lib = new VideoLibrary();
fillData();
}

private void fillData() {
try {
final String URL = "http://gdata.youtube.com/feeds/api/users/" + channelName + "/uploads?v=2&alt=jsonc";
HttpGet get = new HttpGet(URL);
HttpResponse response = client.execute(get);
String jsonString = EntityUtils.toString(response.getEntity());
JSONObject json = new JSONObject(jsonString);
JSONArray jsonArray = json.getJSONObject("data").getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject items = jsonArray.getJSONObject(i);
String title = items.getString("title");
String thumbUrl = items.getJSONObject("thumbnail").getString("sqDefault");
String url = items.getJSONObject("player").getString("default");
lib.addVideo(new Video(title, url, thumbUrl));

}

} catch (JSONException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (ClientProtocolException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IOException e) {
e.printStackTrace();
}
}

public VideoLibrary getLib() {
return lib;
}
}

public class SxePhil extends Activity { //class that makes up the interactive end of
//the app, here the JSON data is put in a list
private ListView list;
private GetVideos g;
private VideoLibrary videoLibrary;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sxephil);
list = (ListView) findViewById(R.id.sxephilList);
g = new GetVideos("sxephil");
videoLibrary = g.getLib();

ArrayList<String> titles = new ArrayList<String>();
for (int i = 0; i < 25; i++) {
titles.add(videoLibrary.getVideos().get(i).getTitle());
}


ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.simplerow, titles);
list.setAdapter(adapter);
}
}

基本上我尝试的是实现这里使用的线程:http://blog.blundell-apps.com/show-youtube-user-videos-in-a-listview/

在我的代码中,因为这个项目是建立在一个旧的 sdk 上的,所以我想可以说是对其进行现代化改造。看看GetYoutube***类和MainActivity类就是钱所在

最佳答案

您应该使用 AsyncTask甚至更好,Loader ,它们会自动为您处理胎面

关于java - 安卓开发 : How do I integrate threads in this?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12100102/

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