Android复选框错误“;“在空对象引用上”;
我试图做一个复选框,当它被选中时,它将删除listview中的文本字段元素。我非常确定我做的每件事都是正确的,包括在XML中设置复选框的ID,并在我想要使用的类上声明它,但我仍然得到空对象错误 我已经通读了这个主题的所有问题和答案,我也尝试了所有的问题和答案,但我仍然得到一个错误。有人能帮我确定错误可能在哪里吗 提前非常感谢您的帮助=) 类文件Android复选框错误“;“在空对象引用上”;,android,checkbox,reference,null,Android,Checkbox,Reference,Null,我试图做一个复选框,当它被选中时,它将删除listview中的文本字段元素。我非常确定我做的每件事都是正确的,包括在XML中设置复选框的ID,并在我想要使用的类上声明它,但我仍然得到空对象错误 我已经通读了这个主题的所有问题和答案,我也尝试了所有的问题和答案,但我仍然得到一个错误。有人能帮我确定错误可能在哪里吗 提前非常感谢您的帮助=) 类文件 package com.puyakul.prin.psychic_shopping; import... public class MainList
package com.puyakul.prin.psychic_shopping;
import...
public class MainListView extends AppCompatActivity {
//================DATABASE=====================//
private ShoppingListDatabase databaseConnection;
private SQLiteDatabase db;
public ListView ListView_mainListView;
public ArrayList<ShoppingList> lists;
public AppCompatCheckBox checkBox_doneCheck;
public TextView textView_listname;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//================DATABASE Connection================//
databaseConnection = new ShoppingListDatabase(this);
db = databaseConnection.open();
//important!!!
setContentView(R.layout.activity_main_list_view);
getLists();
}
public void getLists(){
....
******Original here, but I delete by acident******
checkBox_doneCheck = findViewById(R.id.checkBox_doneCheck);
checkBox_doneCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (checkBox_doneCheck.isChecked()) {
textView_listname.setPaintFlags(textView_listname.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
else{
textView_listname.setPaintFlags(textView_listname.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
}
}
});
}
<android.support.v7.widget.AppCompatCheckBox
android:id="@+id/checkBox_doneCheck"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:checked="false"/>
您缺少
xml
和java
代码之间的关联。
添加此行:
checkBox_doneCheck = findViewById(R.id.checkBox_doneCheck)
这就是为什么您有
NullPointerException
您从未初始化过复选框_doneCheck
,请在onCreate
中尝试此选项:
setContentView(R.layout.activity_main_list_view);
checkBox_doneCheck = (AppCompatCheckBox) findViewById(R.id.checkBox_doneCheck);
getLists();
您可能还希望对这些变量执行类似的操作:
ListView\u mainListView
textView\u列表项
复选框\u doneCheck=findViewById(R.id.checkBox\u doneCheck)
,同时尝试缩短文本=(嗨,谢谢你的回复,我添加了行,但仍然面临错误非常感谢你的回复,我添加了它,但仍然存在错误。
setContentView(R.layout.activity_main_list_view);
checkBox_doneCheck = (AppCompatCheckBox) findViewById(R.id.checkBox_doneCheck);
getLists();