WebViewDemo

Posted on Dec 28, 2009 (4 years ago). Seen 37,086 times. 11 comments. Permalink Feed
Member since Dec 23, 2009
Location: Oakland
Stream Posts: 0
Tagged as: Android Tutorial

In this demo, we get to view a web address in a totally different way by sidestepping the default browser and creating our own custom webviewer.

The key to creating the custom webviewer is the MyWebViewClient class that extends the WebViewClient class. With its key method shouldOverrideUrlLoading(view,url) that gives control to application when a new url is loaded in the provided view.


WebViewDemo.java
Code:

package org.example.webviewdemo;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;

public class WebViewDemo extends Activity {
private WebView webView;
private EditText urlField;
private Button goButton;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

// Create reference to UI elements
webView = (WebView) findViewById(R.id.webview_compontent);
urlField = (EditText)findViewById(R.id.url);
goButton = (Button)findViewById(R.id.go_button);

// workaround so that the default browser doesn't take over
webView.setWebViewClient(new MyWebViewClient());

// Setup click listener
goButton.setOnClickListener( new OnClickListener() {
public void onClick(View view) {
openURL();
}
});

// Setup key listener
urlField.setOnKeyListener( new OnKeyListener() {
public boolean onKey(View view, int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_ENTER) {
openURL();
return true;
} else {
return false;
}
}
});

}

/** Opens the URL in a browser */
private void openURL() {
webView.loadUrl(urlField.getText().toString());
//webView.requestFocus();
}

private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}



main.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">

<EditText
android:id="@+id/url"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:lines="1"
android:layout_weight="1.0" android:hint="http://"/>

<Button
android:id="@+id/go_button"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/go_button"
/>

</LinearLayout>

<WebView
android:id="@+id/webview_compontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1.0"
/>
</LinearLayout>

Do not forget
1. To give the AndroidManifestfile.xml the necessary internet permission:
<uses-permission android:name="android.permission.INTERNET" />

2. And for this setup in the strings.xml file to add <string name="go_button">Go</string> in between <resources> tag


Output

Source
http://thenewcircle.com/static/tutorials/WebViewDemo.zip

Comments

Posted on Oct 18, 2010
Photo Mr Fantastic
Designer
Freelance
Member since Oct 18, 2010
Great tutorial. It shows up on my Htc Hero android phone, but does not work. In actuality none of the tutorials work on my phone. Can you please direct me to find out why. I'm a flash designer/developer who just began studying/tutorials on how create apps for android and would appreciate any help.

thanks,

rmc...
Posted on Oct 19, 2010
Photo Marko Gargenta
@MarkoGargenta
Member since Jan 19, 2007
Location: San Francisco
Mr. Fantastic, it's super hard to figure out the problem when all I have going on is "it doesn't work" . The details are in your logcat, and so is likely the answer. Hope this helps.
Posted on Dec 9, 2010
Photo Glenn Nelson
No Org
Member since Dec 9, 2010
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.view.View;


public class MyWebProg extends Activity {
/** Called when the activity is first created. */
private WebView webview;



@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

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

// workaround so that the default browser doesn't take over
//Compile error: MyWebViewClient cannot be resolved to a type
webview.setWebViewClient(new MyWebViewClient());

webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("http://www.msn.com");

//Compile error:Illegal modifier for the local class MyWebViewClient; only abstract or final is permitted
private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}

}

}

Great example! However, I am running into compile errors. webview works, but when I add your
"MyWebViewClient" to prevent the default browser from taking control, Java complains that the MyWebViewClient class has an illegal modifier and only abstract or final is permitted (See code and comments above). I tried to match your example, but what am I doing wrong?

Thanks in advance,
Glenn
Posted on Dec 9, 2010
Photo Marko Gargenta
@MarkoGargenta
Member since Jan 19, 2007
Location: San Francisco
Check your {} and make sure it's an inner class. Hard to see when code is not formatted. But, it's a Java syntax error, so should be easy to figure out with Eclipse or similar.
Posted on Dec 9, 2010
Photo Glenn Nelson
No Org
Member since Dec 9, 2010
Thank you! That was the problem. My MyWebViewClient class was inside the closing brace of my onCreate class. Silly me.
Posted on Mar 19, 2011
Photo Radu Motisan
N/A
Member since Mar 19, 2011
Here is my own variant of a custom WebBrowser for Android using the Webview control:
http://www.pocketmagic.net/?p=1776
The HTML Source code is intercepted using a Jvascript.
Posted on Sep 1, 2011
Photo Hitesh Dhamshaniya
Mobile Technology
DRC
Member since Sep 1, 2011
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

String html="<html> <body> <p>Als Ergänzung zum bestehenden Team suchen wir für unseren Partner einen zuverlässigen, teamfähigen Bauabdichter/Flachdachisoleur.</p><p>Gerne würden wir Ihnen näheres von dieser interessanten Stelle in einem Gespräch berichten, wenn Sie:</p><p> </p><ul><li>über einen eidg.Berufsabschluss als Spengler, Polybauer, Bauabdichter oder Flachdachisoleur verfügen oder über jahrelange Berufserfahrung verfügen und dies mit entsprechenden Arbeitszeugnissen belegen können.</li><li> 100% dichte Schweissnähte interlassenund über die nötigen Zertifikate verfügen Bsp. Sarnafil, Sarnafil T usw. </li><li>sich gewohnt sind selbstständig zu arbeiten</li><li>die deutsche Sprache mündlich und schriftlich verstehen</li><li>den Führerschein Kat. B besitzen</li><li>an einer langfristigen Anstellung interessiert sind</li><li>körperlich robust gebaut sind</li> </ul><p>Im Gegenzug wird Ihnen in dieser Anstellung geboten:</p><ul><li>faire Entlöhnung</li><li>aufgestelltes kollegiales Team</li><li>Einsatzbetrieb mit gutem Ruf</li><li>langfristige Anstellung</li><li>selbstständiges Arbeiten</li> <li>nach Eignung können auch Servicearbeiten dazukommen</li></ul><p>Siefühlen sichangesprochen? Zögern Sie nicht und kontaktieren Sie uns.</p><p> </p></body> </html>";

WebView wvDis = (WebView)findViewById(R.id.webviewDisplay);

wvDis.loadData(html, "text/html", "utf-8");
}
why this give message web page not available while I am trying to load data not url
Posted on Sep 29, 2011
Photo Jake Hart
Application Developer
Render Plus Systems
Member since Sep 29, 2011
I tried this code and it works great. However, if I load a page that contains text input boxes, when I tap the input the web view flashes black for a second (actually it is flashing transparent, because if I set the background color for the layout underneath the WebView, that is the color I see). And sometimes it doesn't even redraw except for the input that has focus.

Every other WebView example I can find has this same problem -- does anyone know how to fix it?
--Thanks
Posted on Nov 24, 2011
Photo Mahesh Patil
Mahesh
Mahesh
Member since Nov 24, 2011
Hi,
I tried to run the WebViewDemo on emulator but, I am facing error "Web Page not available" error.
Can you please help me out.
for u r app i have set permission also <uses-permission android:name="android.permission.INTERNET"></uses-permission>

In emulator default search browser I am able to access the internet. I have set all proxy and port.


Regards,
Mahesh
Posted on Nov 24, 2011
Photo Mahesh Patil
Mahesh
Mahesh
Member since Nov 24, 2011
Hi,
I downloded the source from http://thenewcircle.com/static/tutorials/WebViewDemo.zip and tried to run on emulator still same problem.

Is any additional settings required?

My emulator is able to access the internet. I have set proxy and port.
Posted on Aug 16, 2012
Photo Mradul Pandey
Metadesign Solutions
Member since May 6, 2011
can we do pre caching for webview ?