Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

findViewById returns null for WebView

I'm trying to build an android app, which just consists of a webview. I took the example from android dev site and modified it. But as simple as it looks, every call to findViewById results in a null pointer. The .java file:

    public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        WebView webView = (WebView) findViewById(R.id.webview);
        // returns null pointer 
        webView.loadUrl("file:///android_asset/index.html");

        setContentView(webView);
    }
}

The layout file:

<LinearLayout 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"
    android:orientation="horizontal"
    tools:context=".MainActivity" >

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

</LinearLayout>

And I put following line into the manifest:

<uses-permission android:name="android.permission.INTERNET" />

I'm puzzled ...

like image 529
Michael Avatar asked Sep 22 '13 10:09

Michael


2 Answers

Change to

public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mylayout); // muylayout is your layout.xml
    WebView webView = (WebView) findViewById(R.id.webview);
    // returns null pointer 
    webView.loadUrl("file:///android_asset/index.html");
}
}

You need to set the content of your layout to the activity before calling findViewById. findViewById looks for a view with the id provided in the current layout inflated.

like image 72
Raghunandan Avatar answered Oct 17 '22 14:10

Raghunandan


Just in case the accepted answer is not working. Since i have two different layouts for phone and tablet but only one have WebView which cause findViewById() get null.

like image 27
siripan Avatar answered Oct 17 '22 13:10

siripan