2014-09-27 141 views
0

我試圖獲取HTML源代碼,但它凍結了應用程序。 我不知道是什麼問題,我添加了互聯網許可 我從一個網站獲取了這段代碼,但它並不適合我。它工作,直到我按下按鈕,然後它只是凍結。從WebView獲取網站源代碼

我希望有人能幫助我,這裏是我使用的代碼:

public class MainActivity extends Activity { 

    private String HTML = ""; 
    EditText tv; 
    private ProgressDialog m_ProgressDialog; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 

    setContentView(R.layout.activity_main); 

    Button btn = (Button)findViewById(R.id.button1); 
    tv = (EditText)findViewById(R.id.editText1); 
    btn.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View arg0) { 
      // TODO Auto-generated method stub 
      getHTML("http://m.Facebook.com/"); 
     } 
    }); 
} 

public void getHTML(String paramString) 
{ 
    try 
    { 
    BufferedInputStream localBufferedInputStream = new BufferedInputStream(new URL(paramString).openConnection().getInputStream()); 
    ByteArrayBuffer localByteArrayBuffer = new ByteArrayBuffer(50); 
    while (true) 
    { 
     int i = localBufferedInputStream.read(); 
     if (i == -1) 
     { 
     HTML = new String(localByteArrayBuffer.toByteArray()); 
     handler.sendEmptyMessage(0); 
     return; 
     } 
     i = (byte)i; 
     localByteArrayBuffer.append(i); 

    } 
    } 
    catch (Exception localException) 
    { 
    while (true) 
     this.HTML = "Error!"; 
    } 
} 


private Handler handler = new Handler() 

{ 
    public void handleMessage(Message paramMessage) 
{ 

    EditText localEditText = (EditText)MainActivity.this.findViewById(R.id.editText1); 

    MainActivity.this.m_ProgressDialog.dismiss(); 

    localEditText.setText(MainActivity.this.HTML); 

} 

}; 


} 

回答

0

除了做你的主線程網絡工作(一大禁忌在Android的 - 使用一個的AsyncTask),你的錯誤可能是發生在這裏:

public void getHTML(String paramString) { 
    try { 
     BufferedInputStream localBufferedInputStream = new BufferedInputStream(new URL(paramString).openConnection().getInputStream()); 
     ByteArrayBuffer localByteArrayBuffer = new ByteArrayBuffer(50); 
     while (true) { 
      int i = localBufferedInputStream.read(); 
      if (i == -1) { 
       HTML = new String(localByteArrayBuffer.toByteArray()); 
       handler.sendEmptyMessage(0); 
       return; 
      } 
      i = (byte) i; 
      localByteArrayBuffer.append(i); 

     } 
    } catch (Exception localException) { 
     while (true) // <<< this will create an infinite loop when an error occurs 
      this.HTML = "Error!"; 
    } 
} 

嘗試從您的catch語句刪除while (true)

0

這對WebView有什麼影響?你有一個NetworkOnMainThreadExeption。你必須把你的代碼放在AsyncTask或Thread中來防止這種情況發生。