2015-10-06 22 views
0

我不知道如何使這個代碼在AsyncTask工作,我搜索了多個例子,但它不斷崩潰。我在互聯網上發現了這個簡單的代碼,我想調整它以從文本字段獲取URL並獲取HTML代碼。我發現它必須在AsyncTask中,否則它將無法工作,但即使在AsyncTask中,我也無法使其工作。這是我的代碼:我如何使這個代碼成爲一個AsyncTask?

String ETURL = ETURLInput.getText().toString(); 

try { 
    URL TestURL = new URL(ETURL); 

    BufferedReader bufferReader = new BufferedReader(
        new InputStreamReader(TestURL.openStream())); 

    String outputCode; 
    while ((outputCode = bufferReader.readLine()) != null) 
    TVCode.setText(outputCode); 
    bufferReader.close(); 
} catch (Exception e) { 
    TVCode.setText("Oops, something went wrong.") 

} 

} 

這是需要在ActionListener內部執行的代碼。所以當我點擊按鈕時,它應該在AsyncTask中執行此代碼。

希望有人能幫助我。

+0

作爲一個猜測,你的'AsyncTask'崩潰,因爲你是從'doInBackground'試圖更新UI(通過你的'setText'電話) 。來自'LogCat'的錯誤,以及將此代碼移動到'AsyncTask'的代碼將有所幫助。 – PPartisan

+0

@PPartisan感謝您的回答。我嘗試了這一點,我得到以下錯誤:引起:java.net.MalformedURLException:未找到協議:,,,, java.lang.RuntimeException:執行doInBackground(),,,,, java.lang時發生錯誤。 SecurityException:權限被拒絕(缺少INTERNET權限?)。我正確使用了Internet權限,因此我不知道爲什麼會出現此錯誤。 – JI38D

+0

在這種情況下,你見過與此錯誤信息有關的其他答案嗎?即[權限被拒絕(缺少INTERNET權限?)](http://stackoverflow.com/questions/25135595/permission-denied-missing-internet-permission) – PPartisan

回答

0

你忘了添加openConnection,在創建你的URL對象後添加:URLConnection conn = TestURL.openConnection();

,使其與一的AsyncTask工作,你可以做的是存儲類變量的字符串,在doInBackGround回國,並在你的onPostExecute使用它。

方法,你可以在你的AsyncTask創建的一個例子:

protected String getContentUrl(String URL) { 
    String line=null; 
    String result=""; 
    try { 
    try { 
     URL url; 
     // get URL content 
     url = new URL(URL); 
     URLConnection conn = url.openConnection(); 

     // open the stream and put it into BufferedReader 
     BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
     line=br.readLine(); 
     while (line!= null) { 
     result=result+line; 
     line=br.readLine(); 
     } 
     //System.out.print(result); 
     br.close(); 

     return result; 
    } catch (MalformedURLException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    } catch (Exception e) { 
    e.printStackTrace(); 
    } 

    return null; 

然後你得到你的結果這樣的doInBackGround

getContentUrl(YOUR URL HERE) 

存儲這個值在一個字符串,並將其返回。然後,你可以用它在你的onPostExecute

希望它能幫助:)

相關問題