Today we’ll show you how to create a WebView app for a website. This is pretty easy to do, and should take you less than 30 minutes if you’re just starting out with Android.
Even though it is just a simple app, it also provides more than just the webview, giving you the starting point for handling loading errors, displaying loading screens between pages if required, and so on.
Let’s get started.
First of all, create a simple Android App, and leave all the options as default. Then, in the AndroidManifest.xml file, insert this just above the
<uses-permission
android:name="android.permission.INTERNET" />
Then, we need to create the XML layout for the app. In res/layout/activity_main.xml, just paste these over what was already written (take note of the WebView tag, which will be used to display the website, and the LinearLayout tag, which contains the error messages and the button to reload):
<
?
xml
version="1.0"
encoding="utf-8"?>
<
RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.codingfy.webviewdemo.MainActivity">
<
WebView
xmlns
:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/><
LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="16dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="16dp"
android:id="@+id/networkerror"
android:orientation="vertical"
android:visibility="gone">
<
TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/network_error"
/><
TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/network_error2"
/>
<
Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/retry"
android:id="@+id/retryConnecting"/>
<
/
LinearLayout>
<
/
RelativeLayout>
Now come the Strings. Write these in /res/values/strings.xml (these are the strings that represent the messages you see displayed in the app):
<
string name="network_error"
>Sorry, but there was a network problem:-(
</
string>
<
string name="network_error2"
>
Please check your connection and then press the button below.<
/
string>
<
string name="retry"
>
Retry.<
/
string>
And here comes the Java code of the app. Write all these in MainActivity.java, but make sure you replace the package name with your package name (you can find it in the manifest file):
package com.codingfy.webviewdemo; import android.app.ProgressDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.LinearLayout; public class MainActivity extends AppCompatActivity { WebView myWebView; private ProgressDialog progressBar; static MainActivity theInstance; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); theInstance = this; //We use the progress bar to display a message to the user while pages load. //For big pages, this might stay on the screen a long time while most of the content //is already loaded, so you might want to remove it. progressBar = ProgressDialog.show(theInstance, "Please wait", "Loading..."); if(progressBar.isShowing()){ progressBar.dismiss(); } final LinearLayout networkError = (LinearLayout) findViewById(R.id.networkerror); myWebView = (WebView) findViewById(R.id.webview); WebSettings webSettings = myWebView.getSettings(); webSettings.setJavaScriptEnabled(true); //There is an easier way to just load the page, but we actually do it this way //so we can have control over the loading process, catch loading errors and //display the loading ProgressBar myWebView.setWebViewClient(new WebViewClient(){ boolean ignoreDoneOnce = false; public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); progressBar = ProgressDialog.show(theInstance, "Please wait", "Loading..."); return true; } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(myWebView, url); if(ignoreDoneOnce){ ignoreDoneOnce = false; } else { //Toast.makeText(getApplicationContext(), "Done!", Toast.LENGTH_SHORT).show(); view.clearCache(true); myWebView.setVisibility(View.VISIBLE); networkError.setVisibility(View.GONE); if (progressBar.isShowing()) { progressBar.dismiss(); } } } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { //Toast.makeText(getApplicationContext(), "Oh no! " + description, Toast.LENGTH_SHORT).show(); ignoreDoneOnce=true; myWebView.setVisibility(View.GONE); networkError.setVisibility(View.VISIBLE); if (progressBar.isShowing()) { progressBar.dismiss(); } } }); //The retry button. It goes back to the homepage, you might want to save the loading //link from shouldOverrideUrlLoading in a variable, and load that if this button is pressed Button retryConnecting = (Button)findViewById(R.id.retryConnecting); if (retryConnecting != null) { retryConnecting.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub progressBar = ProgressDialog.show(theInstance, "Please wait", "Loading..."); myWebView.loadUrl("http://google.com/"); } }); } myWebView.loadUrl("http://google.com/"); } //Required for the back button to actually go back. @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // Check if the key event was the Back button and if there's history if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) { myWebView.goBack(); return true; } // If it wasn't the Back key or there's no web page history, bubble up to the default // system behavior (probably exit the activity) return super.onKeyDown(keyCode, event); } }
Thanks for following along! If you have any questions, feel free to comment below!
Pingback: Properly loading data from the web in Android – Programming