findViewById中NullPointerException的错误

最近在弄一个对话框的登录时,发现一个总是报NullPointerException的错误,折腾了两小时,一直没有发现细小的区别。。先上图,一边说明原因

首先是

Activity类中定义的findViewById()

* There are two methods almost all subclasses of Activity will implement:
 *
 * <ul>
 *     <li> {@link #onCreate} is where you initialize your activity.  Most
 *     importantly, here you will usually call {@link #setContentView(int)}
 *     with a layout resource defining your UI, and using {@link #findViewById}
 *     to retrieve the widgets in that UI that you need to interact with
 *     programmatically.
 *
 *     <li> {@link #onPause} is where you deal with the user leaving your
 *     activity.  Most importantly, any changes made by the user should at this
 *     point be committed (usually to the
 *     {@link android.content.ContentProvider} holding the data).
 * </ul>

2.

  private CharSequence mTitle;
      private int mTitleColor = 0;
    final FragmentManagerImpl mFragments = new FragmentManagerImpl();
    final FragmentContainer mContainer = new FragmentContainer() {
        @Override
        public View findViewById(int id) {
            return Activity.this.findViewById(id);
        }
    };

3.

    /**
     * Called when the activity is starting.  This is where most initialization
     * should go: calling {@link #setContentView(int)} to inflate the
     * activity's UI, using {@link #findViewById} to programmatically interact
     * with widgets in the UI, calling
     * {@link #managedQuery(android.net.Uri , String[], String, String[], String)} to retrieve
     * cursors for data being displayed, etc.

4.

 /**
     * Finds a view that was identified by the id attribute from the XML that
     * was processed in {@link #onCreate}.
     *
     * @return The view if found or null otherwise.
     */
    public View findViewById(int id) {
        return getWindow().findViewById(id);
    }

我们调用的findViewById()函数其实有两种(目前我只看到两种,不确定还有没有其他的),一种是Activity类中findViewById()函数

另外一种是View类中定义的findViewById()函数

一般我们在oncreate()方法中使用的(**view)findViewById(R.id.**)既是调用的Activity中的findViewById()函数

而在其他情况写出的***view.findViewById()中调用的是view类中的findViewById()

从这里可以看出这个函数是在寻找在xml中定义的指定id的对象View类中的findViewById()

从这里可以看出我们是从一个view的child view中寻找指定id的对象,所以即使几个layout的XML文件中的View的id号相同的话,只要他们没有相同的父节点,或有相同的父亲节点,但不在父节点及以上节点调用findViewById通过id来查找他们就是没有问题。

使用这个函数的常见问题:

仔细看下边两段代码代码

[xml]

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/LinearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
[xml]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout> 

一段里边Layout没有id这个参数,一段里边有id,虽然代码不同但在outline中显示出来都是

这样在第一种情况下R.id中可以找到LinearLayout这个控件,第二种是没有的哈,这些也是以后要注意的细节

2.在调用view中的findViewById()一定要想好父View是谁!即**view.findViewById()中的**view要找对,如果没有找对父View,返回基本都是null了

1.在另一个view的元素应该用baseView.findViewById()来拿

findViewById()是要指定view的,如果在该view下找不到,自然报null。平时注意养成写view.findViewById()的习惯就不容易错了。

2.findViewById在setContentView(R.layout.main);之前.

即在setContentView调用之前,调用了findViewById去找main布局中的界面元素lv_contactbook,那么所得到的lv一定是null。正确的做法是将上面代码中加粗的哪一行,挪至setContentView方法调用之后即可。

3.clean一下工程,让ID重新生成

这种情况是调用LayoutInflater.inflate将布局xml规定的内容转化为相应的对象。比如有rowview.xml布局文件(比如在自定义Adapter的时候,用作ListView中的一行的内容的布局),假定在自定的Adapter的getView方法中有类似如下的代码:

View rowview = (View)inflater.inflate(R.layout.rowview, parent, false);

TextView tv_contact_id =(TextView)rowview.findViewById(R.id.tv_contact_id);

TextView tv_contactname =(TextView)rowview.findViewById(R.id.tv_contactname);

有时候居然也会发现rowview非空,但tv_contact_id和tv_contactname都是null!仔细看代码,怎么也看不出错误来。到底是什么原因造成的呢?答案是Eclipse造成的,要解决这个问题,需要这个项目clean一次(Project菜单 -> Clean子菜单),这样就OK了。

findViewById中NullPointerException的错误,布布扣,bubuko.com

时间: 2024-08-06 11:31:38

findViewById中NullPointerException的错误的相关文章

《java中异常和错误》

异常和错误的区别. 异常: 在Java中程序的错误主要是语法错误和语义错误,一个程序在编译和运行时出现的错误我们统一称之为异常,它是VM(虚拟机)通知你的一种方式,通过这种方式,VM让你知道,你(开发人员)已经犯了个错误,现在有一个机会来修改它.Java中使用异常类来表示异常,不同的异常类代表了不同的异常.但是在Java中所有的异常都有一个基类,叫做Exception. 错误:它指的是一个合理的应用程序不能截获的严重的问题.大多数都是反常的情况.错误是VM的一个故障(虽然它可以是任何系统级的服务

Spring中的一个错误:使用Resources时报错(The annotation @Resources is disallowed for this location)

在学习Spring的过程中遇到一个错误:在使用注解@resources的时候提示:The annotation @Resources is disallowed for this location 后来来在学问Java网友的时候解决了. 原来的代码是这样的: 1 package com.show.biz; 2 3 import javax.annotation.Resources; 4 5 import com.show.biz.UserBiz; 6 import com.show.dao.Us

GDI+中发生一般性错误的解决办法(转载)

今天在开发.net引用程序中,需要System.Drawing.Image.Save 创建图片,debug的时候程序一切正常,可是发布到IIS后缺提示出现"GDI+中发生一般性错误"的异常.于是开始"摆渡",并寻找到了解决办法:赋予 NETWORK SERVICE 帐户以写权限. 以下为晚上寻找到的资料: 在开发.NET应用中,使用 System.Drawing.Image.Save 方法而导致"GDI+ 中发生一般性错误"的发生,通常有以下三种

nodejs出现events.js:72中抛出错误

作为初学者,我在使用nodejs的过程中遇到了如下的运行错误: events.js:72 throw er; // Unhandled 'error' event ^ Error: listen EADDRINUSE at errnoException (net.js:901:11) at Server._listen2 (net.js:1039:14) at listen (net.js:1061:10) at Server.listen (net.js:1127:5) at Object.<

Eclipse中Tocat运行错误

今天总结一下Eclipse中Tocat运行错误的处理办法: 1.选中service框中的tomcat,右键点击-->clear;之后再添加项目运行: 2.右键点击tomcat-->AddAndRemove-->将tomcat中的项目移除: 3.进入tomcat安装路径,将work里的缓存全部清空: 4.如果以上处理还不能解决,就是java编译时出现问题,可以检查一下Eclipse中的设置: Eclipse-->Project-->Buid AutoMatically选中该选项

[转]GDI+ 中发生一般性错误

在开发.NET应用中,使用 System.Drawing.Image.Save 方法而导致“GDI+ 中发生一般性错误”的发生,通常有以下三种原因:1. 相应的帐户没有写权限.解决方法:赋予 NETWORK SERVICE 帐户以写权限.2. 指定的物理路径不存在.解决方法:在调用 Save 方法之前,先判断目录是否存在,若不存在,则创建.if (!Directory.Exists(dirpath))Directory.CreateDirectory(dirpath);3. 保存的文件已存在并因

应用JSTL屏蔽页面中出现的错误,比如除数为0

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%String path = request.getContextPath();String basePath = re

配置错误_“/”应用程序中的服务器错误。

配置错误 “/”应用程序中的服务器错误. 配置错误 说明: 在处理向该请求提供服务所需的配置文件时出错.请检查下面的特定错误详细信息并适当地修改配置文件. 分析器错误消息: 在应用程序级别之外使用注册为 allowDefinition='MachineToApplication' 的节是错误的.如果在 IIS 中没有将虚拟目录配置为应用程序,则可能导致此错误. 源错误: 行 20: </compilation> 行 21: 行 22: <authentication mode="

libxml2 在mingw中 xmlfree连接错误问题

libxml2 在mingw中 xmlfree连接错误问题 2013年10月02日 ⁄ 综合 ⁄ 共 1527字 ⁄ 字号 小 中 大 ⁄ 评论关闭 原地址:http://blog.csdn.net/hongqun/article/details/6009684 libxml2是一套非常好用的xml库,官网是http://www.libxml.org/,但是天知道是什么原因,此网页无法访问. 好不容易下载下来,在mingw中却问题多多. 第一个问题: 也就是说,编译通过了,但是在链接过程中找不到