2011-10-06 128 views
0

我試圖從android應用程序的web服務中獲取xml。我正在運行此代碼,但錯誤消息是'應用程序意外停止。請再試一次'。我不確定它是一個應用程序異常,因爲代碼的每一次安寧都在try塊中。什麼是錯誤?Android從aspx web服務中獲取xml

public class AndroidTest extends Activity { 

      private static final String URL = "http://webservice.url/is/here.aspx"; 
      TextView v; 

      public void onCreate(Bundle savedInstanceState) { 
      try { 
       super.onCreate(savedInstanceState); 
       v = new TextView(this); 
       setContentView(v); 
       new Obtainer().execute(); 
      } catch (Exception ex) { 
       Toast.makeText(this, ex.toString(), Toast.LENGTH_LONG).show(); 
      } 
     } 

     private class Obtainer extends AsyncTask<Void, Void, Void> { 

      protected Void doInBackground(Void... params) { 
       BufferedReader in = null; 
       try { 
        HttpClient client = new DefaultHttpClient(); 
        HttpGet request = new HttpGet(); 
        request.setURI(new URI(URL)); 
        HttpResponse response = client.execute(request); 
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
        StringBuffer sb = new StringBuffer(""); 
        String line = ""; 
        while ((line = in.readLine()) != null) { 
         sb.append(line + "\n"); 
        } 
        in.close(); 
        v.setText(sb.toString()); 
       } catch (Exception ex) { 
        Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_LONG).show(); 
       } 
       return null; 
      } 
     } 
    } 

編輯:現在拋出儘管這一類(獲取器)的成立是爲了解決它的異常android.os.NetworkOnMainThreadException。

+0

當你看到這樣的錯誤時,你可以檢查logcat以獲取更多信息。你也可以在這裏發佈logcat的異常消息嗎? – spatulamania

回答

0

答案很簡單 - 我們不能在非ui線程中運行Toast顯示方法,也無法在TextView中運行它。