Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/187.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
setChecked-in复选框返回java.lang.NullPointerException_Java_Android - Fatal编程技术网

setChecked-in复选框返回java.lang.NullPointerException

setChecked-in复选框返回java.lang.NullPointerException,java,android,Java,Android,我希望你能在这方面帮助我。我有一个带有复选框控件的XML,我想将其更改为“按代码检查” 当Android Studio编译时,代码在“cb.setChecked(true)”中有一个错误。致命异常:主 java.lang.NullPointerException CheckBox cb = (CheckBox) findViewById(R.id.checkBox); cb.setChecked(true); XML文件 <?xml version="1.0" encoding="utf

我希望你能在这方面帮助我。我有一个带有复选框控件的XML,我想将其更改为“按代码检查”

当Android Studio编译时,代码在“cb.setChecked(true)”中有一个错误。致命异常:主 java.lang.NullPointerException

CheckBox cb = (CheckBox) findViewById(R.id.checkBox);
cb.setChecked(true);
XML文件

<?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="wrap_content"
          android:background="#ff8989"
          android:id="@+id/backColor"
          android:divider="@drawable/ic_launcher"
          android:longClickable="true">

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="20dp">

    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/checkBox"
        android:layout_gravity="left|top"
        android:checked="false"/>

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="..."
        android:id="@+id/txt_tarea"
        android:paddingLeft="10dp"
        android:textSize="15sp"/>

    </LinearLayout>
</LinearLayout>


谢谢。

请检查您提供给findViewById的id。它是否存在于layout.xml中。在调用此之前,还必须使用该布局文件对视图进行充气。请验证这些要点,我认为您的问题会得到解决。

您没有给我们足够的信息(您的
onCreate()
和布局XML会有所帮助),但我认为
cb
为空应该是相当明显的
findViewById()
在找不到具有给定ID的视图时返回null,因此我猜想您的布局缺少要查找的
复选框
元素。共享布局xml文件该复选框包含正确ID的xml。您可能没有调用
setContentView()
在调用
findViewById()之前使用该布局。我可以毫无问题地访问TextView。复选框被放入具有正确id的XML中。您在onCreate中为您的活动调用了什么?您是否在setContentView中使用相同的布局文件?我有一个ListView,其中我膨胀了一个XML,其中有一个带有TextView的复选框。我可以无错误地访问TextView和setText,但使用复选框控件时我会出现此错误。您上次的评论使问题变得非常令人困惑,错误是什么?我使用了
checkBox cb=(checkBox)findviewbyd(R.id.checkBox)这是错误的。正确的代码是
CheckBox cb=(CheckBox)item.findviewbyd(R.id.CheckBox)