2013-10-09 76 views
0

文字我找到了答案
包括在主要活動的你「的onCreate」方法,下面兩行:創建Android應用程序,讀取URL

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
StrictMode.setThreadPolicy(policy); 

我創建了一個Android應用程序,將閱讀的文本從一個URL並在屏幕上顯示文本。當我的輸入是「http://web.njit.edu/~halper/it114/l2d.txt」時它崩潰,但當我的輸入是「http://web.njit.edu/~halper/it114/l2d.txt」時什麼都不做。我試圖將android.permission.INTERNET添加到Manifest.xml,我仍然得到相同的結果。
致命異常:主要
java.lang.IllegalStateException:無法執行所致活動
的方法:java.lang.reflect.InvocationTargetException
產生的原因:android.os.NetworkOnMainThreadException
非常感謝您對你的時間

public void enter(View v) { 

EditText input = (EditText) findViewById(R.id.edit_file); 
TextView tv = (TextView) findViewById(R.id.text_main); 

try { 
URL url = new URL(input.getText().toString());    
Scanner scan = new Scanner(url.openStream()); 
while(scan.hasNext()) 
tv.append(scan.nextLine()); 
} 

catch(MalformedURLException e) { e.printStackTrace(); } 
catch(IOException e) {e.printStackTrace();} 
} 
+1

什麼是錯誤?請發佈您的LogCat。 –

+0

致命例外:main java.lang.IllegalStateException:無法在android.view.View上執行活動 的方法$ 1.onClick(View.java:3633) at android.view.View.performClick(View.java: 4240) 在android.view.View $ PerformClick.run(View.java:17722) 在android.os.Handler.handleCallback(Handler.java:730) 在android.os.Handler.dispatchMessage(Handler.java: 92) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:5303) at java.lang.reflect.Method.invokeNative(Native Method) – user2843187

+0

發佈你所有的logcat。 – nedaRM

回答

0

這是爲我工作:

public String getTextFromTheMagicKingom() throws ClientProtocolException, IOException { 
     String url = "http://web.njit.edu/~halper/it114/l2d.txt"; 
     HttpClient client = new DefaultHttpClient(); 
     HttpGet request = new HttpGet(url); 
     HttpResponse response = client.execute(request); 
     BufferedReader rd = new BufferedReader(
      new InputStreamReader(response.getEntity().getContent())); 

     StringBuffer result = new StringBuffer(); 
     String line = ""; 
     while ((line = rd.readLine()) != null) { 
      result.append(line); 
     } 
     return result.toString(); 
    } 

一請在您的評論中更正格式。有一個愉快的一天._。/

0
Caused by: android.os.NetworkOnMainThreadException 

由於蜂窩,我們已經不再被允許讓UI線程網呼叫,因爲他們是潛在的緩慢,這將是愚蠢的掛UI,同時等待一臺服務器。您需要將網絡代碼放在單獨的Thread中,或使用AsyncTask或Volley等庫。

如果這僅僅是測試的事情了,那麼你也可以把的StrictMode這就是禁止從該線程的網絡接入...

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
StrictMode.setThreadPolicy(policy); //Disabling StrictMode is not recommended. It is much better to make Asynchronous network calls... 

您應該已經張貼在您進行網絡請求的代碼以及。看起來你正在爲自己做練習,所以我建議只使用一個線程,並在獲得響應時使用它的runOnUiThread()方法。 AsyncTask擁有比您需要更多的功能...