views:

1318

answers:

2

I've been banging my head against a wall this afternoon trying to get a WebView to work. Below is the code in the main class:

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

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

        webview = (WebView) findViewById(R.id.webview);
        webview.getSettings().setJavaScriptEnabled(true);
        // WORKS
        //webview.loadUrl("http://www.google.com");
        // DOESN'T WORK
        //webview.loadUrl("http://www.theregister.co.uk");
        //webview.loadData("<html><body>hello</body></html>", "text/html", "utf-8");
        //webview.loadDataWithBaseURL("fake://", "<html><body>hello</body></html>", "text/html", "utf-8", "http://www.theregister.co.uk/");

    }
}

This is Google's "Hello, Webview" example. If I use a WebView and try to access www.google.com then it works fine. If I try to access any other site then it fails including loadData and it just displays a black screen in the emulator. In the end I would like to read from a local file.

is included under the manifest tag and the XML schema is the same as the Hello Webview example.

Am I missing something obvious here? :(

A: 

Try UTF-8 instead of utf-8 for your latter two attempts. I have no problem loading http://www.theregister.co.uk using the same code -- try loading it in the built-in Browser app, and if that fails, you're perhaps encountering some sort of firewall/proxy issue.

Here are a few projects demonstrating simple uses of WebView, from one of my books.

CommonsWare
+3  A: 

Try changing

android:layout_width="wrap_content"
android:layout_height="wrap_content"

to

android:layout_width="fill_parent"
android:layout_height="fill_parent"

in your main.xml top level LinearLayout

It should look like this:

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

    <WebView 
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
    />

</LinearLayout>
Tyler
I had the same problem as the poster, this fixed it for me. Thanks Tyler!
Carlos Rendon
You mean to say that the layout parameters have any influence on what urls the webview can load or not?
Mathias Lin