I have an HTTP Request that parses an XML file. I'm trying to connect to internet from an asyntask but I have not been able
I do this and works by putting the code inside a thread, but not inside an AsycTask The problem I have is that the HTTP Request is called within a String with this line of code:
String xml = parser.getXmlFromUrl(URL);
Running this
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
}
};
As I mentioned, the HTTP Request is within a thread, but I always find errors when I try to put it inside a AsycTask ... I do not know how do it.
I have been referred to the documentation of AsycTask and have read many times, I have searched tutorials, but I could not build it correctly.
After two days, i begin to be a little desperate
I put the complete code for my work, if anyone can tell me how to replace a AsyncTask thread, I'll be very grateful.
Thank you very much and regards
full activity:
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);
}
}
The HTTP request can be run in the doInBackground function of Asynctask and your runnable is the onPostExecute function. The result is this :
public class XmlTask extends AsyncTask<String, Void, String>{
public String doInBackground(String... urls){
String url = urls[0];
// Place your getXmlFromUrl content here
return xml;
}
public void onPostExecute(String xml){
// Your XML parsing staement here
}
}
In this code, Thread and runnable are unnecessary.
And in your activity just tap:
new XmlTask().execute("http://yoururl");
The following code should work for you. Try it:
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;
// constructor
public void XMLParser() {
}
/**
* Cogiendo el XML de la URL mediante HTTP request
* @param url string
* */
public String getXmlFromUrl(String url) {
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();
}
return xml;
}
/*
* @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));
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list=(ListView)findViewById(R.id.list);
AsyncTask<Void, Void, Void> ast = new AsyncTask<Void, Void, Void>(){
ProgressDialog p;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
p = new ProgressDialog(EditTextDemoActivity.this);
//write code to start the progress dialog
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
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);
}
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
p.dismiss();
adapter=new MinAdapter(this, songsList);
lst.setAdapter(adapter);
}
};
ast.execute();
}
}
I have implemented the code using AsyncTask
. You don't need any other Thread
to implement background activity when you are using AsyncTask
. I have left a small part of coding (to create and display a progress dialog) as an exercise for you.
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.