为什么这不起作用? Android中的空指针

时间:2014-06-12 07:19:33

标签: android

检查以下代码并帮我解决小伙子问题。我不知道我做错了什么。请检查并帮助我

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


            wv = (WebView) findViewById(R.id.webView1); // here is the error. What is wrong in this line?

            wv.setWebViewClient(new Callback());

            loadTime(); // execution is not coming till this part.
        }

//直到此处才执行,在findViewByID

崩溃
        public void loadTime()
        {
            String page = "<html> <body> <a href = 'hi'>" + DateUtils.formatDateTime(this
                    , new Date().getTime(), DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME) +
                    "</a></body></html>";

            wv.loadData(page, "text/html", "UTF-8");
        }


        private class Callback extends WebViewClient
        {
            @Override

            public boolean shouldOverrideUrlLoading(WebView w, String s)
            {
                loadTime();

                return true;
            }
        }


        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }

    }

每当我尝试执行它时,在webview上给出空指针。我不知道如何解决这个问题,请帮助,非常感谢

4 个答案:

答案 0 :(得分:3)

在活动中,您需要先调用setContentView()来设置布局。只有在那之后才能通过findViewById()找到它的任何内容。确保您实际设置了一个内容视图,其中包含您正在尝试查找的ID的视图。

答案 1 :(得分:0)

因为您没有使用设置内容视图而没有内容视图,所以您不会调用您的XML,这就是您获得NPE的原因。请尝试以下代码: -

    super.onCreate(savedInstanceState);
    setContentView(R.layout.home_screen);
    wv = (WebView) findViewById(R.id.webView1); // here is the error. What is wrong in this line?

    wv.setWebViewClient(new Callback());

    loadTime(); 

答案 2 :(得分:0)

onCreate()中,需要在

之前致电setContentView(R.layout.yourlayoutxmlname);
wv = (WebView) findViewById(R.id.webView1);  

这样就可以识别WebView。

抛出空指针异常,因为编译器不知道在哪里查找WebView,在哪种布局中,为您的活动。

在进一步编程之前,请仔细阅读以下内容:

  1. Android programming setcontentview
  2. Activity, its lifecycle and other details - android developers

答案 3 :(得分:0)

请在撰写setContentView(R.layout.main)之前添加findViewByID。对于活动,您应在初始化ID之前调用setContentView()