gpt4 book ai didi

android - 异步任务类不适用于较新的 Android 版本

转载 作者:行者123 更新时间:2023-11-30 04:00:50 26 4
gpt4 key购买 nike

我想解析 xml,所以我编写了代码,它可以工作到 2.3,但在最新版本上它不起作用,所以我阅读了 asynctask 并修改了我的代码,但我的 imageview 仍然是空白的,我在 logcat 上没有收到任何错误表示 Asynctask 的实现有问题。

{
setContentView(R.layout.actionbar);
String URL = "http://ws.audioscrobbler.com/2.0/?method=artist.search&artist=ricky_martin&api_key=97855e265470056987425832aa9aa81&limit=" + 1 + "&page=" + 1;
new FetchXMLAsyncTask().execute(URL);
icon = (ImageView) findViewById(R.id.icon);
}

class FetchXMLAsyncTask extends AsyncTask<String, Void, Void> {
String name;
@Override
protected Void doInBackground(String... params) {
try {
// TODO Auto-generated method stub
final String Artist = "artist";
final String KEY_NAME = "name";
final String API = "b25b959554ed76058ac220b7b2e0a026";
final String KEY_IMAGE ="image";
//final String KEY_COST = "cost";
//final String KEY_DESC = "description";
String URL = params[0];
XmlParser parser = new XmlParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr;
expr = xpath.compile("//image[@size=\"large\"]");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
Element e = (Element) nl.item(i);
String name = parser.getValue(e, KEY_NAME);// name child value
image = parser.getValue(e, KEY_IMAGE);
// Toast.makeText(this, "name"+name+"url"+image, Toast.LENGTH_SHORT).show();
} }catch (XPathExpressionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//do something after parsing is done
URL thumb_u;
try {
thumb_u = new URL(image);
Drawable thumb_d = Drawable.createFromStream(thumb_u.openStream(), "src");
icon.setImageDrawable(thumb_d);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

最佳答案

Starting Honeycomb AsyncTasks 默认一次启动一个。也许您还有其他一些任务挂起并阻止了这个任务的运行(新任务正在等待旧任务完成,因为它不会并行运行)。

启动 android 3.0 你应该在 THREAD_POOL_EXECUTOR 中启动任务

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
} else {
task.execute(params);
}

关于android - 异步任务类不适用于较新的 Android 版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12530225/

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