2012-02-09 149 views
0

我與模擬器一起工作,嘗試從網站獲取文本。alertdialog的錯誤:「應用程序的主要活動有 意外停止,請重試」。從網站閱讀文本

public void testr(View view) throws IOException, URISyntaxException 
    { 
    URL websiteurl = new URL("http://test..."); 
    BufferedReader in = new BufferedReader(
     new InputStreamReader(
     websiteurl.openStream())); 

    String inputLine; 
    AlertDialog alertbox = new AlertDialog.Builder(this).create(); 
    while ((inputLine = in.readLine()) != null) 
    alertbox.setMessage(inputLine.toString()); 
    in.close(); 

alertbox.show(); 

    } 
+0

後logcat的錯誤消息。 – kosa 2012-02-09 20:42:11

回答

0

如果您是在Android 2.3或更高版本,那麼你可能運行到該操作系統殺死做網絡IO UI線程中的所有過程,你好像在片斷做上述情況。

將你的網絡io放在後臺,例如:使用AsyncTask。看看docs for AsyncTask

0
  URL url = new URL("website"); 
     ReadableByteChannel rbc = Channels.newChannel(url.openStream()); 
     rbc = in; 

使用此

0
try { 
    // Create a URL for the desired page 
    URL url = new URL("mysite.com/thefile.txt"); 

    // Read all the text returned by the server 
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); 
    String str; 
    while ((str = in.readLine()) != null) { 
     // str is one line of text; readLine() strips the newline character(s) 
    } 
    in.close(); 
} catch (MalformedURLException e) { 
} catch (IOException e) { 
} 
+0

我嘗試了這些代碼,但它不起作用。它是同樣的錯誤「應用程序mainactivity意外停止,請再試一次」。我使用android 2.2與模擬器...我與異步任務有什麼關係?請舉個例子... – user1198014 2012-02-10 20:11:39