How to Load URL and PDF file in WebView

Hello Friends today we are going to learn about WebView and how to load URL and PDF file in android WebView.first we talk about what is webview in android.


Q. What is WebView?
Ans : WebView is a view that display web pages inside android application and if we want to display HTML Pages like As UI we can use WebView.

Example :- 
1.use in XML

<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/webview"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
/>
  
2. use after create an object

WebView browser = (WebView) findViewById(R.id.webview);
  OR
WebView browser = new wEBvIEW(this); 





Full code of  WebView


package com.artofandroid.activity;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class WevViewPdf extends AppCompatActivity {
    WebView mWebview;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mWebview  = new WebView(this);
        mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript
        final Activity activity = this;

        mWebview.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                activity.setTitle("Loading...");
                activity.setProgress(progress * 100);
                if(progress == 100)
                    activity.setTitle(R.string.app_name);
            }
        });

        mWebview.setWebViewClient(new WebViewClient() {
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
            }
        });
        mWebview .loadUrl("http://docs.google.com/");
        setContentView(mWebview );
    }
}



Ho to Open PFD File  In Webview

Ans :- basically android not provide to open pdf directly bot we can open PDF by following below:-

·         Use a third party library (unfortunately, most open source pdf libs are GPL)
·         Open a pdf viewer app via an Intent
·         Use Google docs in a webview

if you want to open pdf webview you can use Google docs URl like below example

String myPdfUrl = "http://example.com/awesome.pdf";
String url = "http://docs.google.com/gview?embedded=true&url=" + myPdfUrl;
Log.i(TAG, "Opening PDF: " + url);
webView.getSettings().setJavaScriptEnabled(true); 
webView.loadUrl(url);

1 comments:

thanks for useful post.....

Reply