FindViewById returns null for WebView

I am trying to create an android application that just consists of a web view. I gave an example from the Android developer site and modified it. But as simple as it seems, every call to findViewById results in a null pointer. .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); } } 

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 the following line in the manifest:

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

I am puzzled ...

+4
source share
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"); } } 

Before calling findViewById must configure the contents of your layout. findViewById looks for the view with the identifier specified in the current layout, inflated.

+9
source

Just in case, the accepted answer does not work. Since I have two different layouts for phone and tablet, but only one has a WebView that call findViewById (), get zero.

+1
source

All Articles