2013-08-30 24 views
-1

我的應用程序從站點讀取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(); 
       } 
      } 
     }); 
    } 

調用它,但申請凍結了一段時間,當該方法被調用。怎樣成爲?如何在背景上做到這一點?

+0

抱歉等等等等 –

+0

是U將在GETPAGE的AsyncTask? – KOTIOS

+1

你應該使用一個線程或asynctask進行網絡相關的操作 – Raghunandan

回答

0

您正在UI線程上運行它。不要這樣做。改爲使用AsyncTask

0

您的代碼表示您在主UI中使用Strict Mode策略執行網絡相關操作。強烈建議不要這樣做。使用AsynTask來完成此任務。

1
class RequestTask extends AsyncTask<String, String, String>{ 

    @Override 
    protected String doInBackground(String... uri) { 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpResponse response; 
     String responseString = null; 
     try { 
      response = httpclient.execute(new HttpGet(uri[0])); 
      StatusLine statusLine = response.getStatusLine(); 
      if(statusLine.getStatusCode() == HttpStatus.SC_OK){ 
       ByteArrayOutputStream out = new ByteArrayOutputStream(); 
       response.getEntity().writeTo(out); 
       out.close(); 
       responseString = out.toString(); 
      } else{ 
       //Closes the connection. 
       response.getEntity().getContent().close(); 
       throw new IOException(statusLine.getReasonPhrase()); 
      } 
     } catch (ClientProtocolException e) { 
      //TODO Handle problems.. 
     } catch (IOException e) { 
      //TODO Handle problems.. 
     } 
     return responseString; 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     super.onPostExecute(result); 
     //Do anything with response.. 
    } 
} 

然後,您可以通過一個請求:

new RequestTask().execute("http://stackoverflow.com"); 
+0

然後,但我的XML解析器將不會等到該任務結束 –

+0

哦。我明白 –

+0

onPostExecute你wl找到結果字符串 –

相關問題