Android webview loaddata 给出 NullPointerException

发布于 2024-10-18 02:08:17 字数 319 浏览 0 评论 0原文

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

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

我已经给出了 在清单中。但是上面的代码正在生成 NullPointerException 。谁能指出我的代码中的问题吗?

I have used a webview named Testview to load html data in the webview. for that I am using the following code.

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

I have given <uses-permission android:name="android.permission.INTERNET" /> in the manifest. But this above loine of code is generating NullPointerException. Can anyone point out the problem in my code?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

总以为 2024-10-25 02:08:17

正如 @m0s 在评论中指出的:确保 Textview 已初始化

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.

As @m0s pointed in comment: make sure Textview is initialized:

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

Also, it is a Java custom to write class names with first letter capitalized (WebView) and instances with first letter in lower-case (textview), so that they are easily distinguished.

Update:

If this line returns null:

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

then you most probably forgot to call:

setContentView(R.layout.main);

in your activity.onCreate() method. The javadoc of findViewById(int) says:

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

That's what setContentView() does (processes the layout XML):

Set the activity content from a layout resource. The resource will be inflated,
adding all top-level views to the activity.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文