我的應用程序從站點讀取xml。我有這個代碼來獲取XML內容。Android應用程序freezs在調用Http時獲取函數
public String getPage(String url){
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build();
StrictMode.setThreadPolicy(policy);
BufferedReader in = null;
String data = null;
try
{
HttpClient client = new DefaultHttpClient();
URI website = new URI(url);
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
response.getStatusLine().getStatusCode();
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while ((l = in.readLine()) !=null){
sb.append(l + nl);
}
in.close();
data = sb.toString();
return data;
} finally{
if (in != null){
try{
in.close();
return data;
}catch (Exception e){
e.printStackTrace();
}
}
}
} catch (Exception e) {
//return e.toString();
return "No Internet Connection";
//e.printStackTrace();
}
}
,我從這個
public void axtarHandler_run(){
runOnUiThread(new Runnable() {
public void run() {
TextView axtarish_key = (TextView) findViewById(R.id.axtarish_key);
String netice;
try {
netice = getPage("http://somedomain.com/search.php?query="+URLEncoder.encode((String) axtarish_key.getText().toString(),"UTF-8"));
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
final XMLParser parser = new XMLParser();
String xml = netice; // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
final 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));
// adding HashList to ArrayList
songsList.add(map);
}
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(parentActivity, songsList, R.layout.list_row);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Element e = (Element) nl.item(position);
String music_id = parser.getValue(e, KEY_ID);
String music_name = parser.getValue(e, KEY_TITLE);
parentActivity.play_music_forsearch(Integer.toString(position), music_id, music_name);
}
});
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
調用它,但申請凍結了一段時間,當該方法被調用。怎樣成爲?如何在背景上做到這一點?
抱歉等等等等 –
是U將在GETPAGE的AsyncTask? – KOTIOS
你應該使用一個線程或asynctask進行網絡相關的操作 – Raghunandan