2012-02-09 152 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