How to Save Webview Content and Load Again in Android

Android WebView is used to display HTML in an android app. We tin can utilise android WebView to load HTML page into android app.

Android WebView

Android WebView component is a full-fledged browser implemented as a View subclass to embed it into our android application.

Importance Of Android WebView

For HTML lawmaking that is limited in terms of scope, nosotros can implement the static method fromHtml() that belongs to the HTML Utility grade for parsing HTML-formatted cord and displaying it in a TextView.

TextView can return elementary formatting similar styles (bold, italic, etc.), font faces (serif, sans serif, etc.), colors, links, and so forth.

However, when it comes to complex formatting and larger telescopic in terms of HTML, then TextView fails to handle information technology well. For example browsing Facebook won't be possible through a TextView.

In such cases, WebView will be the more advisable widget, as it can handle a much wider range of HTML tags. WebView can also handle CSS and JavaScript, which Html.fromHtml() would simply ignore.

WebView can as well help with common browsing metaphors, such as history list of visited URLs to support backwards and frontwards navigation.

Nevertheless WebView comes with its ain set up of cons such as information technology's a much more expensive widget to use, in terms of memory consumption than a TextView. The reason for this increased memory is because WebView is powered by WebKit/Glimmer that are open source Web rendering engine to ability content in browsers like Chrome.

Android WebView Case

Android WebView component is inserted into the XML layout file for the layout we want the WebView to exist displayed in. In this example we insert it into the activity_main.xml file as shown below:

                          <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"     xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent"     android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"     android:paddingRight="@dimen/activity_horizontal_margin"     android:paddingTop="@dimen/activity_vertical_margin"     android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">      <WebView         android:id="@+id/webview"         android:layout_alignParentTop="true"         android:layout_alignParentLeft="truthful"         android:layout_width="match_parent"         android:layout_height="match_parent"/> </RelativeLayout>                      

Android Studio WebView Code

WebView component is initialized in the MainActivity using its id defined in the activity_main.xml as shown in snippet below:

                          WebView webView = (WebView) findViewById(R.id.webview);                      

Android WebView loadUrl

Once nosotros've obtained a reference to the WebView we can configure information technology and load URLs via HTTP. WebView loadUrl() method is used to load the URL into the WebView every bit shown below:

                          webView.loadUrl("https://www.journaldev.com");                      

Earlier nosotros showtime toying around with the url there are two disquisitional aspects nosotros should take a look at:

  1. Supporting JavaScript: JavaScript is past default turned off in WebView widgets. Hence spider web pages containing javascript references won't work properly. To enable java script the following snippet needs to exist called on the webview example:
                                      getSettings().setJavaScriptEnabled(truthful);                              
  2. Adding Permissions: To fetch and load the urls in the WebView we need to add together permissions to access the cyberspace from inside the app else information technology won't be able to load the webpages. The post-obit line of lawmaking needs to be added in the AndroidManifest.xml file above the awarding tag as shown below:
                                      <?xml version="i.0" encoding="utf-viii"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android"     package="com.journaldev.webview" >      <uses-permission android:name="android.permission.INTERNET" />      <awarding         android:allowBackup="true"         android:icon="@mipmap/ic_launcher"         android:label="@string/app_name"         android:theme="@way/AppTheme" >         <activeness             android:name=".MainActivity"             android:label="@string/app_name" >             <intent-filter>                 <action android:proper name="android.intent.action.MAIN" />                  <category android:proper name="android.intent.category.LAUNCHER" />             </intent-filter>         </action>     </application>  </manifest>                              

The MainAcivity class below contains all the features discussed till now.

                          package com.journaldev.webview;  import android.app.Activeness; import android.os.Packet; import android.webkit.WebSettings; import android.webkit.WebView;  public class MainActivity extends Activity {      @Override     protected void onCreate(Parcel savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          WebView webView = (WebView) findViewById(R.id.webview);          WebSettings webSettings = webView.getSettings();         webSettings.setJavaScriptEnabled(true);          webView.loadUrl("https://www.journaldev.com");     }  }                      

Setting the WebViewClient

The default beliefs when a user clicks on a link within the webpage is to open the systems default browser app. This can pause the user feel of the app users.

To keep page navigation within the WebView and hence within the app, we need to create a subclass of WebViewClient, and override its shouldOverrideUrlLoading(WebView webView, String url) method.

Here is how such a WebViewClient bracket would look:

                          private class MyWebViewClient extends WebViewClient {     @Override     public boolean shouldOverrideUrlLoading(WebView webView, String url) {         render false;     } }                      

When the shouldOverrideUrlLoading() method returns false, the URLs passed as parameter to the method is loaded inside the WebView instead of the browser.

To distinguish between the URLs that are loaded within the app and browser the following code needs to exist added in the shouldOverrideUrlLoading() method:

                          if(url.indexOf("journaldev.com") > -1 ) return false;         return true;                      

Notation: Returning true doesn't signify that the url opens in the browser app. In fact the url won't be opened at all. To load the url into the browser an intent needs to fired. The post-obit bracket contains all the configurations nosotros've added.

                          package com.journaldev.webview;  import android.app.Activity; import android.content.Intent; import android.internet.Uri; import android.webkit.WebView; import android.webkit.WebViewClient;   public form WebViewClientImpl extends WebViewClient {      private Activity activity = zippo;      public WebViewClientImpl(Activeness activeness) {         this.activeness = activeness;     }      @Override     public boolean shouldOverrideUrlLoading(WebView webView, String url) {         if(url.indexOf("journaldev.com") > -1 ) return false;          Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));         activity.startActivity(intent);         return true;     }  }                      

The constructor takes Activity as a parameter to fire an intent in the browser.

Before instantiating this subclass in the MainActivity lets wait at another important feature.

Navigation WebView with Back Button

If we click the back push button in the app developed so far we see that the application returns to the abode screen even though we've navigated through a few pages inside the WebView itself. To become through the browsing history on pressing dorsum push button we need to modify the dorsum button office as shown in the snippet below:

                          @Override     public boolean onKeyDown(int keyCode, KeyEvent event) {         if ((keyCode == KeyEvent.KEYCODE_BACK) && this.webView.canGoBack()) {             this.webView.goBack();             return true;         }          render super.onKeyDown(keyCode, event);     }                      

The onKeyDown() method has been overridden with an implementation that offset checks if the WebView can go back. If the user has navigated away from the showtime page loaded inside the WebView, then the WebView can go back.

The WebView maintains a browsing history just like a normal browser. If there is no history then it volition result in the default behavior of back push button i.eastward. exiting the app.

Post-obit is the code for MainActivity with the above features included.

                          packet com.journaldev.webview;  import android.app.Activity; import android.bone.Parcel; import android.view.KeyEvent; import android.webkit.WebSettings; import android.webkit.WebView;  public class MainActivity extends Action {      individual WebView webView = null;      @Override     protected void onCreate(Parcel savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          this.webView = (WebView) findViewById(R.id.webview);          WebSettings webSettings = webView.getSettings();         webSettings.setJavaScriptEnabled(true);          WebViewClientImpl webViewClient = new WebViewClientImpl(this);         webView.setWebViewClient(webViewClient);          webView.loadUrl("https://www.journaldev.com");     }       @Override     public boolean onKeyDown(int keyCode, KeyEvent outcome) {         if ((keyCode == KeyEvent.KEYCODE_BACK) && this.webView.canGoBack()) {             this.webView.goBack();             return truthful;         }          render super.onKeyDown(keyCode, event);     }  }                      

Below image shows the output produced by our project, yous can run across that WebView is loaded with a preassigned url.

android webview example

Alternatives for Loading Content in the WebView

Till now we've just used loadUrl() method to load the contents in the WebView. Hither we'll run across the other ways to load content later a quick briefing of the usages of loadUrl().

loadUrl() works with:

  • https:// and https://URLs
  • file:// URLs pointing to the local filesystem
  • file:///android_asset/ URLs pointing to one of your applications avails
  • content:// URLs pointing to a ContentProvider that is publishing content
    available for streaming

Instead of loadUrl() we can apply loadData() by which nosotros can display snippets or whole of the HTML lawmaking in the method. There are ii flavors of loadData(). The simpler ane allows us to provide the content, the MIME type, and the encoding, all as strings. Typically, MIME type will exist text/html and the encoding volition be UTF-8 for ordinary HTML as shown below:

                          webView.loadData("<html><body>Hello, world!</body></html>",                   "text/html", "UTF-8");                      

Beneath is the output when the above snippet is added in the MainActivity every bit shown below:

                          bundle com.journaldev.webview;  import android.app.Activity; import android.bone.Bundle; import android.view.KeyEvent; import android.webkit.WebSettings; import android.webkit.WebView;  public form MainActivity extends Activeness {      private WebView webView = cypher;      @Override     protected void onCreate(Parcel savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          this.webView = (WebView) findViewById(R.id.webview);          WebSettings webSettings = webView.getSettings();         webSettings.setJavaScriptEnabled(truthful);          WebViewClientImpl webViewClient = new WebViewClientImpl(this);         webView.setWebViewClient(webViewClient);          //webView.loadUrl("https://www.journaldev.com");         webView.loadData("<html><body>Hello, world!</body></html>", "text/html", "UTF-8");     }       @Override     public boolean onKeyDown(int keyCode, KeyEvent event) {         if ((keyCode == KeyEvent.KEYCODE_BACK) && this.webView.canGoBack()) {             this.webView.goBack();             return true;         }          return super.onKeyDown(keyCode, event);     }  }                      

android webview

There is also a loadDataWithBaseURL() method. This takes, among other parameters, the base of operations URL to use when resolving relative URLs in the HTML. Whatever relative URL (due east.g., <img src="images/sample.png">) will be interpreted as being relative to the base URL supplied to loadDataWithBaseURL().

The historyUrl parameter is the URL to write into the WebView internal navigation history for the HTML loaded into the WebView. The following snippet shows a image for it:

                          String baseUrl    = "https://www.journaldev.com"; String data       = "Relative Link"; String mimeType   = "text/html"; String encoding   = "UTF-8"; String historyUrl = "https://www.journaldev.com";  webView.loadDataWithBaseURL(baseUrl, information, mimeType, encoding, historyUrl);                      

This brings an terminate to android WebView instance tutorial. You can download concluding android webview project from below link.

correiadayinceds.blogspot.com

Source: https://www.journaldev.com/9333/android-webview-example-tutorial

0 Response to "How to Save Webview Content and Load Again in Android"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel