我有一个解析 XML 文件的 HTTP 请求。我正在尝试从 asyntask 连接到互联网,但我无法
我这样做并通过将代码放在线程中而不是在 AsycTask 中来工作我遇到的问题是 HTTP 请求是在使用以下代码行的字符串中调用的:
String xml = parser.getXmlFromUrl(URL);
运行这个
public String getXmlFromUrl(String url) {
Thread t= new Thread(){
public void run() {
xml = null;
try {
Log.i("Log1","Parse");
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://api.androidhive.info/music/music.xml");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mHandler.post(mUpdateResults);
}
};
t.start();
return xml;
}
final Runnable mUpdateResults =new Runnable (){
public void run(){//2
}
};
正如我所提到的,HTTP 请求在一个线程中,但是当我尝试将它放在 AsycTask 中时,我总是会发现错误......我不知道该怎么做。
我已经参考了 AsycTask 的文档并阅读了很多次,我搜索了教程,但我无法正确构建它。
两天后,我开始有点绝望
我为我的工作放了完整的代码,如果有人能告诉我如何替换 AsyncTask 线程,我将非常感激。
非常感谢和问候
完整的活动:
public class PruebasActivity extends Activity {
static final String URL = "http://api.androidhive.info/music/music.xml";
// XML node keys
static final String KEY_SONG = "song"; // parent node
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_ARTIST = "artist";
static final String KEY_DURATION = "duration";
static final String KEY_THUMB_URL = "thumb_url";
private ArrayList<HashMap<String, String>> data;
ArrayList<HashMap<String, String>> songsList;
ListView list;
LazyAdapter adapter;
String xml;
final Handler mHandler=new Handler();
// constructor
public void XMLParser() {
}
/**
* Cogiendo el XML de la URL mediante HTTP request
* @param url string
* */
public String getXmlFromUrl(String url) {
Thread t= new Thread(){
public void run() {
xml = null;
try {
Log.i("Log1","Parse");
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://api.androidhive.info/music/music.xml");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mHandler.post(mUpdateResults);
}
};
t.start();
return xml;
}
final Runnable mUpdateResults =new Runnable (){
public void run(){//2
}
};
/*
* @param XML string
* */
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
/*
* @param elem element
*/
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
/*
* @param Element node
* @param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list=(ListView)findViewById(R.id.list);
songsList = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // Cogiendo XML de la URL
Document doc = parser.getDomElement(xml); // Cogiendo DOM de los elementos
NodeList nl = doc.getElementsByTagName(KEY_SONG);
// looping through all song nodes <song>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
// adding HashList to ArrayList
songsList.add(map);
}
// Pasando datos parseados del adaptador al arrayList
adapter=new MinAdapter(this, songsList);
list.setAdapter(adapter);
}
}