我正在尝试从assets目录加载一个html页面.我尝试了这个,但它失败了.
public class ViewWeb extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); WebView wv; wv = (WebView) findViewById(R.id.webView1); wv.loadUrl("file:///android_asset/aboutcertified.html"); // fails here setContentView(R.layout.webview); } }
我在LogCat中没有任何明显的错误...
您在设置"内容"视图之前获取WebView,因此wv可能为null.
public class ViewWeb extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.webview); WebView wv; wv = (WebView) findViewById(R.id.webView1); wv.loadUrl("file:///android_asset/aboutcertified.html"); // now it will not fail here } }
无论何时创建活动,都必须setcontentview
在超级调用后添加(您的布局).因为setcontentview
将xml绑定到您的活动中,这就是您获得的原因nullpointerexception
.
setContentView(R.layout.webview); webView = (WebView) findViewById(R.id.webView1); wv.loadUrl("file:///android_asset/xyz.html");
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); WebView wb = new WebView(this); wb.loadUrl("file:///android_asset/index.html"); setContentView(wb); } keep your .html in `asset` folder