XML 파일을 구문 분석하는 HTTP 요청이 있습니다. 내가 asyntask에서 인터넷에 연결하기 위해 노력하고있어하지만 난AsyncTask 내의 HTTP 요청
내가 스레드 내부의 코드를 넣어이와 일을 할 수 있지만, 아닌 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 요청 스레드 내에서,하지만 난 그것을 넣어하려고 할 때 난 항상 오류를 발견 AsycTa 내부 내가 어떻게하는지 모르겠다.
저는 AsycTask의 문서를 참조했으며 여러 번 읽었습니다. 자습서를 검색했지만 올바로 작성할 수 없습니다. 나는 내 작품의 전체 코드를 삽입
이 후 일, 난 사람이 어떻게 AsyncTask를 스레드를 교체하는 말해 줄 수 있다면, 나는 매우 감사 할 것, 조금 절망하기 시작합니다.
대단히 감사전체 활동에 관하여 : HTTP 요청이 AsyncTask를의 doInBackground 기능에서 실행할 수 있습니다
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);
}
}
스택 추적과 함께 AsyncTask에서 시도 할 때 사용하는 코드를 게시하면 도움이 될 것이라고 생각합니다. – bytebender