【问题标题】:Android webview loaddata giving NullPointerExceptionAndroid webview loaddata 给出 NullPointerException
【发布时间】:2011-06-30 07:29:29
【问题描述】:

我使用了一个名为Testview 的webview 在webview 中加载html 数据。为此,我正在使用以下代码。

Testview.loadData("<html><body>helloindia</body></html>", "text/html", "utf-8");

我在清单中给出了<uses-permission android:name="android.permission.INTERNET" />。但是上面这段代码正在生成NullPointerException。谁能指出我代码中的问题?

【问题讨论】:

  • 你能添加整个代码sn-p吗?
  • 你确定Testview已经初始化了吗?

标签: android html webview nullpointerexception loaddata


【解决方案1】:

正如@m0s 在评论中指出的那样:确保 Textview is initialized:

textview = new WebView(this);  // used inside an Activity

另外,Java 的习惯是将类名首字母大写(WebView),实例首字母小写(textview),以便于区分。

更新:

如果此行返回 null:

Textview = (WebView)this.findViewById(R.id.testview)

那么你很可能忘记打电话了:

setContentView(R.layout.main);

在您的 activity.onCreate() 方法中。 findViewById(int) 的 javadoc 说:

Finds a view that was identified by the id attribute from the XML THAT WAS 
PROCESSED in onCreate(Bundle).

这就是setContentView() 所做的(处理布局 XML):

Set the activity content from a layout resource. The resource will be inflated,
adding all top-level views to the activity.

【讨论】:

  • Textview = (WebView)this.findViewById(R.id.testview);
  • 实际上我已经在 view.OnClickListener 中更改了视图,并为包含 WebView 的新视图设置了一个新的 xml。 setContentView(R.layout.weblayout); testview = (WebView)this.findViewById(R.id.testview);当我在 findViewById 之前删除“this”时,问题就解决了。但是这行代码在Activity的onCreate(Bundle savedInstanceState)中运行正常。你能告诉我背后的原因吗?
  • view.OnClickListener() 中的 this 指的是匿名类,而不是封闭的视图类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
  • 2011-04-27
  • 2016-10-15
  • 2012-09-07
  • 1970-01-01
相关资源
最近更新 更多