2012-04-06 111 views
1

android中的webview在加載url時多次加載一次。 以下是代碼。WebView在android中加載url不止一次android

public boolean shouldOverrideUrlLoading(WebView view, String url) 
      { 

       if (url.contains(".pdf")) { 
        String[] spliturl = url.split("http://someurl/"); 
        String googleurl = "http://docs.google.com/viewer?embedded=true&url="; 
        System.out.println("Google Url"+googleurl); 
        System.out.println("spliturl"+spliturl[1]); 
        view.loadUrl(googleurl+spliturl[1]); 
       } 
       else 
        view.loadUrl(url); 

       return true; 
      } 
     }); 

我分裂的網址,因爲它包含多個網址要通過谷歌文檔查看器呈現PDF文檔。 第一次url被正確拆分並且url被連接在google文檔中打開,但webview在spliturl [1]處通過給出ArrayIndexOutOfBoundsException再次執行。 有人能讓我知道爲什麼這是再次執行。 謝謝。

+0

可能會更樣本,如果你直接在打開PDF導航器: 字符串googleDocsUrl =「http://docs.google.com/viewer?url="+documentUrl; \t \t \t Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.parse(googleDocsUrl),「text/html」); startActivity(intent); – 2012-04-06 08:05:07

回答

1

您應經常檢查,如果數組的大小大於所要求的指標更多:

if (url.contains(".pdf") && url.split("http://someurl/").size()>2){ 
// your code 
} 

不知道爲什麼它被調用雖然 - 也許多個重定向。

+0

謝謝完美答案。 – Mukunda 2012-04-06 08:02:15

2

我不知道爲什麼它被稱爲多次,但解決的辦法是處理它在onPageStarted而非shouldOverrideUrlLoading

boolean calledOnce=false; 

public boolean shouldOverrideUrlLoading(WebView view, String url) { 
     view.loadUrl(url); 

     return true; 
    } 

public void onPageStarted(WebView view, String url, Bitmap favicon) { 
    if (url.contains(".pdf") && !calledOnce) { 
      String[] spliturl = url.split("http://someurl/"); 
      String googleurl = "http://docs.google.com/viewer?embedded=true&url="; 
      System.out.println("Google Url"+googleurl); 
      System.out.println("spliturl"+spliturl[1]); 
      url = googleurl+spliturl[1]; 
      calledOnce = true; 
     }  
    super.onPageStarted(view, url, favicon); 
}