im building an app that should allow users to click a link to a pdf document in a webview and display it in the view. im using google docs viewing pdf files work, but my problem is that i only want the method to work for pdf links and not every link, heres my code:
public class HelloWebViewActivity extends Activity
{
WebView mWebView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("https://nuigalway.blackboard.com/webapps/login/");
mWebView.setWebViewClient(new HelloWebViewClient());
}
private class HelloWebViewClient extends WebViewClient
{
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
String googleDocs = "https://docs.google.com/viewer?url=";
mWebView.loadUrl(googleDocs + url);
return true;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack())
{
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
i think the error is in the shouldOverrideUrlLoading method. Is there any method that would allow me to open the pdf url only when the file itself is clicked in the webview?
Your shouldOverrideUrlLoading logic is incorrect. The url parameter is the url which is getting clicked. So you want to intercept any pdf links, but let the webview handle all other urls normally.
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
if (url.endsWith(".pdf"))
{
// Load "url" in google docs
}
else
{
// Load all other urls normally.
view.loadUrl(url);
}
return true;
}
I think this is the simplest code. Try this:
private class HelpClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.endsWith(".pdf")){
// Load "url" in google docs
String googleDocs = "https://docs.google.com/viewer?url=";
view.loadUrl(googleDocs + url);
}
else {
// Load all other urls normally.
view.loadUrl(url);
}
// view.loadUrl(url);
frameLayout.setVisibility(View.VISIBLE);
return true;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With