空指针异常 - findViewById()

Null pointer Exception - findViewById()

提问人:user2629828 提问时间:9/29/2013 最后编辑:westonuser2629828 更新时间:11/13/2021 访问量:62789

问:

谁能帮我找出这个程序可能有什么问题。 在该方法中,为所有 id 返回 null,这会导致稍后出现 null 指针异常。我不明白为什么找不到风景。有什么建议吗?onCreate()findViewById()findViewById()

这是主要代码:

public class MainActivity extends Activity {

    ViewPager pager;
    MyPagerAdapter adapter;
    LinearLayout layout1, layout2, layout3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        layout1 = (LinearLayout) findViewById(R.id.first_View);
        layout2 = (LinearLayout) findViewById(R.id.second_View);
        layout3 = (LinearLayout) findViewById(R.id.third_View);

        adapter = new MyPagerAdapter();
        pager = (ViewPager) findViewById(R.id.main_pager);
        pager.setAdapter(adapter);
    }

    private class MyPagerAdapter extends PagerAdapter
    {

        @Override
        public int getCount() { 
            return 3;
        }

        @Override
        public Object instantiateItem(ViewGroup collection, int position) {

            LinearLayout l = null;

            if (position == 0 )
            {
                l = layout1;
            }
            if (position == 1)
            {
                l = layout2;
            }

            if (position == 2)
            {
                l = layout3;
            }
                collection.addView(l, position);
                return l;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return (view==object);
        }

         @Override
         public void destroyItem(ViewGroup collection, int position, Object view) {
                 collection.removeView((View) view);
         }
    }
}

以及相关的 XML 文件:

activity_main布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:orientation="vertical"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:background="#a4c639">


    <android.support.v4.view.ViewPager
                        android:layout_width="match_parent" 
                        android:layout_height="match_parent" 
                        android:id="@+id/main_pager"/>
</LinearLayout>

activity_first布局:

<?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:id="@+id/first_View">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />

<Button
    android:id="@+id/button1"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button" />

</LinearLayout>

activity_second布局:

 <?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:id="@+id/second_View">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />

</LinearLayout>

activity_third布局:

<?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:id="@+id/third_View">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />

</LinearLayout>
Android NullPointerException onCreate FindViewById

评论


答:

92赞 Ahmad Dwaik 'Warlock' 9/29/2013 #1

findViewById()如果 View 存在于您提供的布局中,则返回 View,否则它将返回 null,这就是发生在您身上的情况。请注意,如果没有 ,并且没有有效的视图到 on,则在调用 之前将始终返回 null。setContentView()setContentView()findViewById()findViewById()setContentView()

这也意味着顶级变量会触发 NPE,因为它们是在 之前调用的,并且扩展为 before 。另请参阅活动生命周期onCreate()setContentView()

例如,如果你然后调用它将返回一个视图,这是你的布局。setContentView(R.layout.activity_first);findViewById(R.id.first_View);

但是,如果您之前调用 ,它将返回,因为您的布局中没有名为 的视图。findViewById(R.id.second_View);setContentView()nullactivity_first.xml@+id/second_View

评论

0赞 user2629828 9/29/2013
我已将所有布局包含在主布局中,并且不再有空指针异常。谢谢你的提示。
7赞 isuru chathuranga 8/24/2014
当我在当前显示视图以外的其他视图上使用它时,该视图就出现了。为了克服这种不需要的行为,我在不使用 setContentView 的情况下引用了视图,如下所示。layout1 = (LinearLayout) View.inflate(this, R.layout.first_View, null);然后要访问其中的任何内容,我可以使用 Button botton = (Button) layout1.findViewById(R.id.button1);只是添加,以便它可能对 sombody 有所帮助。
1赞 Niklas Rosencrantz 11/21/2017
为什么?强迫我们有什么好处?
0赞 Alston 5/31/2019
那么包含未提供的资源的解决方案是什么。setContentView()
2赞 ssantos 9/29/2013 #2

您尝试获取的视图未在布局中定义。您需要以编程方式扩充您尝试添加到寻呼机的视图。activity_main

@Override
public Object instantiateItem(ViewGroup collection, int position) {
    LinearLayout l = null;

    if (position == 0) {
        l = (LinearLayout) View.inflate(this, R.layout.activity_first, null);
    }
    if (position == 1) {
        l = (LinearLayout) View.inflate(this, R.layout.activity_second, null);
    }
    if (position == 2) {
        l = (LinearLayout) View.inflate(this, R.layout.activity_third, null);
    }

    collection.addView(l, position);
    return l;
}

评论

0赞 Denny 2/11/2017
您将如何访问主活动中的视图?
1赞 nebulae 9/29/2013 #3

在访问这些视图之前,请将这些视图添加到寻呼机适配器中。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    adapter = new MyPagerAdapter();
    pager = (ViewPager) findViewById(R.id.main_pager);
    pager.setAdapter(adapter);

    layout1 = (LinearLayout) findViewById(R.id.first_View);
    layout2 = (LinearLayout) findViewById(R.id.second_View);
    layout3 = (LinearLayout) findViewById(R.id.third_View);

}

在寻呼机适配器中:

public Object instantiateItem(View collection, int position) {
    if(position == 0){
        View layout = inflater.inflate(R.layout.activity_first, null);

        ((ViewPager) collection).addView(layout);

        return layout;
    } 
    ... and so forth.

}

从这里,您可以通过 findViewById 访问它们。

0赞 ArronXY 9/29/2013 #4

@Warlock上面说的没错,你应该用正确的方式初始化 LinearLayout layout1、layout2、layout3:

LinearLayout layout1 = (LinearLayout) View.inflate(this, R.layout.first_View, null);
LinearLayout layout2 = (LinearLayout) View.inflate(this, R.layout.second_View, null);
LinearLayout layout3 = (LinearLayout) View.inflate(this, R.layout.third, null);

希望我的建议对你有所帮助

0赞 Charan 9/29/2013 #5

在 Android 中,当您在布局集中查找视图时有效。findViewById(R.id.some_id)

也就是说,如果您设置了布局,请说:

setContentView(R.layout.my_layout);

视图只能在此布局中找到 (my_layout)。

在您的代码中,都是三种不同的布局,并且它们未设置为活动。layout1layout2layout3

0赞 Chinevu Amadi 9/29/2013 #6

该方法必须找到布局中的内容(您在findViewByIdsetContentView)

2赞 Vlad 4/6/2014 #7

有时你需要在 Eclipse 中清理你的项目 (Project - Clean..)。

评论

0赞 Razvan_TK9692 8/12/2021
这为我解决了它 - 这是一个手动步骤是荒谬的,而且错误会损害 ID 查找。.我以为机器总是合乎逻辑的——到底是什么能以这种方式破坏代码?!
0赞 user3635389 5/26/2014 #8

我今天遇到了这个错误,它很容易清除,以至于我“脸部”。

只需尝试将 UI 元素添加到 res/layout-port 目录中的布局 xml 文件中即可!!

3赞 2 revscricket_007 #9

强调后加

对于 Activity 类中的那些情况。

Activity.findViewById(int id)

查找由 onCreate(Bundle) 中处理的 XML 中的属性标识的视图。id


否则,例如 Fragment、Adapter、来自 a 等。ViewLayoutInflater

View.findViewById(int id)

查找具有给定 .如果此视图具有给定的 ID,则返回此视图。id


无论哪种情况,

如果找到,则返回视图否则返回
null。


现在,重新检查您的 XML 文件。确保将正确的值放入 或 中。setContentViewinflater.inflate

对于 Activity,请在 之后调用。findViewByIdsetContentView

然后,确保该布局中有您要查找的视图。确保 为 ,这会将资源添加到值中,以确保您可以从 Java 中找到它。android:id="@+id/..."+@+idR.id

1赞 Will Buffington 5/9/2018 #10

就我而言,这对我来说是一个愚蠢的错误。我在 OnCreate 方法中编写了代码,但它位于代码行之上。一旦我将代码移到这一行下方,应用程序就开始正常工作。setContentView

setContentView(R.layout.activity_main);
-1赞 Aryan Bisht 6/2/2021 #11

当您在 XML 文件中具有许多组件的相同名称时,也会产生此问题。即使它们是不同的布局文件,也应该为每个元素指定一个唯一的名称。 发生此错误的原因是,您在另一个布局文件中具有同名的 XML 元素,并且 android studio 正在尝试访问该元素并显示此错误

0赞 Arsalan Bahojb 11/13/2021 #12

使用适配器来扩充布局,并根据位置搜索视图。

override fun instantiateItem(collection: ViewGroup, position: Int) : ViewGroup {
    val inflater = LayoutInflater.from(mContext)
    val layout = inflater.inflate(mData[position], collection, false) as ViewGroup

    if(position == your_position) {
       val nameOfField: TextView = layout.findViewById(R.id.item_id)
    }