最近在弄一个对话框的登录时,发现一个总是报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的错误的更多相关文章

  1. 《java中异常和错误》

    异常和错误的区别. 异常: 在Java中程序的错误主要是语法错误和语义错误,一个程序在编译和运行时出现的错误我们统一称之为异常,它是VM(虚拟机)通知你的一种方式,通过这种方式,VM让你知道,你(开发 ...

  2. "bower.json 中出现语法错误" 的解决方案之一

    当你用 Visual Studio 2015 Update 3 打开从别处下载的开源项目的时候,如果发现 Bower 提示 "bower.json 中出现语法错误". 请检查一下. ...

  3. ASP.NET Core中显示自定义错误页面-增强版

    之前的博文 ASP.NET Core中显示自定义错误页面 中的方法是在项目中硬编码实现的,当有多个项目时,就会造成不同项目之间的重复代码,不可取. 在这篇博文中改用middleware实现,并且放在独 ...

  4. ASP.NET Core中显示自定义错误页面

    在 ASP.NET Core 中,默认情况下当发生500或404错误时,只返回http状态码,不返回任何内容,页面一片空白. 如果在 Startup.cs 的 Configure() 中加上 app. ...

  5. SQL SERVER 2008:内部查询处理器错误: 查询处理器在执行过程中遇到意外错误

       今天一个同事突然告诉我,以前跑得很正常的一个SQL语句,执行时突然报如下错误:         消息1222,级别16,状态18,第1 行         已超过了锁请求超时时段.        ...

  6. 关于Oracle报“ORA-12514 TNS 监听程序当前无法识别连接描述符中请求服务”错误

    关于Oracle报“ORA-12514 TNS 监听程序当前无法识别连接描述符中请求服务”错误原因:listener.ora中没有指定监听服务器名. 如下是解决思路: 尝试1.通过重启服务的方式启动数 ...

  7. C语言初学者代码中的常见错误与瑕疵(23)

    见:C语言初学者代码中的常见错误与瑕疵(23)

  8. 在Visual Lisp中处理自动化错误

    Handling Automation errors in Visual LISP 翻译自原文Kean's blog:http://through-the-interface.typepad.com/ ...

  9. ASP.NET中处理自定义错误的最佳方式

    要在ASP.NET中处理好自定义错误(Custom Errors)首先要抛弃使用web.config\customErrors. <customErrors mode="RemoteO ...

随机推荐

  1. async/await,了解一下?

    上一篇博客我们在现实使用和面试角度讲解了Promise(原文可参考<面向面试题和实际使用谈promise>),但是Promise 的方式虽然解决了 callback hell,但是这种方式 ...

  2. 【OCP|052】OCP最新题库解析(052)--小麦苗解答版

    [OCP|052]OCP最新题库解析(052)--小麦苗解答版 OCP最新题库解析历史连接(052):http://mp.weixin.qq.com/s/bUgn4-uciSndji_pUbLZfA ...

  3. Windows笔记目录

    Windows笔记目录   Windows介绍 Windows入门--个人感想 初入Linux AD域控 FTP 服务器及权限 Server-U FTP与AD完美集成方案详解 其他 Linux大文件传 ...

  4. Golang学习笔记:channel

    channel channel是goroutine之间的通信机制,它可以让一个goroutine通过它给另一个goroutine发送数据,每个channel在创建的时候必须指定一个类型,指定的类型是任 ...

  5. RHEL(红帽七)的DNS配置

    RHEL7的DNS配置 本文中用到的所有参数均位于文末附录中   查询bind-chroot这个安装包 Yum 安装 bind-chroot 进入named.conf文件 复制以下参数进去 进入这个文 ...

  6. iOS支付宝,微信,银联支付集成封装(上)

    一.集成支付宝支付 支付宝集成官方教程https://docs.open.alipay.com/204/105295/ 支付宝集成官方demo https://docs.open.alipay.com ...

  7. Java课程设计常见技术问题(程序部署、数据库、JSP)

    1. 部署方法 Eclipse下打包 右键点击项目-Export-Runnable JAR file,选择正确的Launch configuration,接下来根据提示可以将项目中用到的jar打入包中 ...

  8. Kafka系列之-Kafka Protocol实例分析

    本文基于A Guide To The Kafka Protocol文档,以及Spark Streaming中实现的org.apache.spark.streaming.kafka.KafkaClust ...

  9. Gradle 1.12用户指南翻译——第四十七章. Build Init 插件

    本文由CSDN博客貌似掉线翻译,其他章节的翻译请参见: http://blog.csdn.net/column/details/gradle-translation.html 翻译项目请关注Githu ...

  10. Android自定义View(LimitScrollerView-仿天猫广告栏上下滚动效果)

    转载请标明出处: http://blog.csdn.net/xmxkf/article/details/53303872 本文出自:[openXu的博客] 1分析 2定义组合控件布局 3继承最外层控件 ...