2011-06-17 13 views
23

Chciałbym wyświetlić komunikat o błędzie, gdy wystąpił błąd podczas ładowania strony z podglądem strony internetowej (brak połączenia). Tak jak dotąd, bez kodu obsługi błędów:Wykrywanie błędu widoku strony i wyświetlenie komunikatu

public class TrackerPage extends Activity { 

    // @Override 
    private WebView webview; 
    private ProgressDialog progressDialog; 

    private boolean error; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     // Get rid of the android title bar 
     requestWindowFeature(Window.FEATURE_NO_TITLE); 

     // Set the XML layout 
     setContentView(R.layout.tracker_page); 

     // Bundle objectbundle = this.getIntent().getExtras(); 
     webview = (WebView) findViewById(R.id.tracker); 

     final Activity activity = this; 

     // Enable JavaScript and lets the browser go back 
     webview.getSettings().setJavaScriptEnabled(true); 
     webview.canGoBack(); 

     webview.setWebViewClient(new WebViewClient() { 
      public boolean shouldOverrideUrlLoading(WebView view, String url) { 
       view.loadUrl(url); 
       return true; 
      } 

      public void onLoadResource(WebView view, String url) { 
       // Check to see if there is a progress dialog 
       if (progressDialog == null) { 
        // If no progress dialog, make one and set message 
        progressDialog = new ProgressDialog(activity); 
        progressDialog.setMessage("Loading please wait..."); 
        progressDialog.show(); 

        // Hide the webview while loading 
        webview.setEnabled(false); 
       } 
      } 

      public void onPageFinished(WebView view, String url) { 
       // Page is done loading; 
       // hide the progress dialog and show the webview 
       if (progressDialog.isShowing()) { 
        progressDialog.dismiss(); 
        progressDialog = null; 
        webview.setEnabled(true); 
       } 
      } 

     }); 

     // The URL that webview is loading 
     webview.loadUrl("http://url.org/"); 
    } 
} 

Jak to zrobić?

Odpowiedz

20

Wszystkie powyższe odpowiedzi są przestarzałe. Należy użyć tego kodu po na stronie wykończone

@Override 
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error){ 
      //Your code to do 
     Toast.makeText(getActivity(), "Your Internet Connection May not be active Or " + error , Toast.LENGTH_LONG).show(); 
    } 
+1

Jak wykorzystać powyższe, jeśli projekt jest ukierunkowany na poziom API <23? – Michael

+0

@Michael, istnieje inna metoda z różnymi parametrami, która została wprowadzona na poziomie API 1 - onReceivedError (WebView, int, String, String) – cdeange

+1

Jeśli nie ma internetu, widzę tylko "nie znaleziono strony" i żadne z tych wywołań zwrotnych są nazywane. Dlaczego? Czy lepiej jest używać nowszego API programu onReceivedError? Zgodnie z dokumentami, jest to wymagane dla każdego komponentu na stronie. Jak mogę to sprawdzić, gdy dotyczy to tylko całej strony? –

27

Jesteś na najlepszej drodze ... Po prostu zaimplementuj onReceivedError i obsłuż błędy, które chcesz.

+4

Zaimplementuj to, ale nie przechwytuje błędów błędów tylko javascript itp. – Codebeat

+4

W przypadku błędów javascript ustaw parametr WebChromeClient nadpisujący onConsoleMessage(). – Alex

15

dodać to po onpagefinished:

public void onReceivedError(WebView view, int errorCod,String description, String failingUrl) { 
      Toast.makeText(Webform.this, "Your Internet Connection May not be active Or " + description , Toast.LENGTH_LONG).show(); 
     } 

Nie zapomnij importować android.widget.Toast;

5

Updated odpowiedź według API 23 Marshmallow

WebViewClient Błędy obsługi błędów

/* 
    * Added in API level 23 replacing :- 
    * 
    * onReceivedError(WebView view, int errorCode, String description, String failingUrl) 
    */ 
    @Override 
    public void onReceivedError(WebView view, WebResourceRequest request, 
      WebResourceError error) { 

     Toast.makeText(getActivity(), 
       "WebView Error" + error.getDescription(), 
       Toast.LENGTH_SHORT).show(); 

     super.onReceivedError(view, request, error); 

    } 

    /* 
     Added in API level 23 
    */ 
    @Override 
    public void onReceivedHttpError(WebView view, 
      WebResourceRequest request, WebResourceResponse errorResponse) { 

     Toast.makeText(getActivity(), 
       "WebView Error" + errorResponse.getReasonPhrase(), 
       Toast.LENGTH_SHORT).show(); 


     super.onReceivedHttpError(view, request, errorResponse); 
    } 

Network Handling

 webView.loadUrl(urlToLoad); 

     if (!isConnected(getActivity())) { 
      Toast.makeText(getActivity(), "You are offline ", Toast.LENGTH_SHORT).show(); 

     } 

    /** 
    * Check if there is any connectivity 
    * 
    * @param context 
    * @return is Device Connected 
    */ 
    public static boolean isConnected(Context context) { 

     ConnectivityManager cm = (ConnectivityManager) context 
       .getSystemService(Context.CONNECTIVITY_SERVICE); 

     if (null != cm) { 
      NetworkInfo info = cm.getActiveNetworkInfo(); 

      return (info != null && info.isConnected()); 
     } 
     return false; 
    } 
2
public class WebClient extends WebViewClient { 

    @Override 
    @TargetApi(Build.VERSION_CODES.M) 
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { 
     super.onReceivedError(view, request, error); 
     final Uri uri = request.getUrl(); 
     handleError(view, error.getErrorCode(), error.getDescription().toString(), uri); 
    } 

    @SuppressWarnings("deprecation") 
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { 
     super.onReceivedError(view, errorCode, description, failingUrl); 
     final Uri uri = Uri.parse(failingUrl); 
     handleError(view, errorCode, description, uri); 
    } 

    private void handleError(WebView view, int errorCode, String description, final Uri uri) { 
     final String host = uri.getHost();// e.g. "google.com" 
     final String scheme = uri.getScheme();// e.g. "https" 
     // TODO: logic 
    } 
} 
Powiązane problemy