如何获取使用android kotlin检查的所有复选框的值?我收到空指针异常

车坛

对于问题的逻辑,您可以参考这个问题:- question Logic

经过很多努力,我走到了这一步。请帮我解决这个问题。

这是活动代码:-

class CheckboxesActivity : AppCompatActivity() {

    lateinit var recyclerView: RecyclerView
    lateinit var adapter: CheckboxAdapter


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_trail)
        recyclerView =findViewById(R.id.trail_rv)

        val list = listOf(
            RowModel(RowType.TopHeader, "", "", false),
            RowModel(RowType.Course, "", "Science", false),
            RowModel(RowType.SubjectRow, "Physics", "Science", false),
            RowModel(RowType.SubjectRow, "Math", "Science", false),
            RowModel(RowType.SubjectRow, "Chemistry", "Science", false),
            RowModel(RowType.Course, "", "Arts", false),
            RowModel(RowType.SubjectRow, "Economics", "Arts", false),
            RowModel(RowType.SubjectRow, "History", "Arts", false),
            RowModel(RowType.SubjectRow, "Political Science", "Arts", false),
            RowModel(RowType.Course, "", "Commerce", false),
            RowModel(RowType.SubjectRow, "Accountancy", "Commerce", false),
            RowModel(RowType.SubjectRow, "Business Studies", "Commerce", false),
            RowModel(RowType.SubjectRow, "Physical Education", "Commerce", false)
        )

        adapter = CheckboxAdapter(this, list)
        adapter.setList(list)
        recyclerView.adapter = adapter
        recyclerView.layoutManager = LinearLayoutManager(this)

        findViewById<Button>(R.id.showTextBtn).setOnClickListener {
            selectedCheckboxes!!.clear()
            val checkboxesValue: String = selectedCheckboxes!!.joinToString(separator = ";")
            findViewById<TextView>(R.id.ShowTextView).text = checkboxesValue
        }

    }
}

这是我的适配器代码:-

class CheckboxAdapter(
    private val context: Context,
    var productList: List<RowModel>,
) : RecyclerView.Adapter<CheckboxAdapter.TableViewHolder>() {


    override fun onBindViewHolder(holder: TableViewHolder, position: Int) {

    val item = productList[position]

        holder.checkBox.setOnCheckedChangeListener(null)
        holder.checkBox.isChecked = item.isChecked

        val params: ViewGroup.MarginLayoutParams =
            holder.checkBox.layoutParams as ViewGroup.MarginLayoutParams

        when (item.rowType) {
            RowType.TopHeader -> {
                holder.checkBox.text = "All Courses"

                holder.checkBox.visibility = View.VISIBLE

                holder.checkBox.typeface = Typeface.DEFAULT_BOLD

                params.setMargins(0, 0, 0, 0)
                holder.checkBox.layoutParams = params

            }
            RowType.Course -> {

                holder.checkBox.visibility = View.VISIBLE
                holder.checkBox.text = item.category


                holder.checkBox.typeface = Typeface.DEFAULT_BOLD
                params.setMargins(0, 0, 0, 0)
                holder.checkBox.layoutParams = params

            }
            RowType.SubjectRow -> {

                holder.checkBox.visibility = View.VISIBLE
                holder.checkBox.text = item.subjectName
                holder.checkBox.typeface = Typeface.DEFAULT
                params.setMargins(convertDpToPixel(20f, context).toInt(), 0, 0, 0)
                holder.checkBox.layoutParams = params
            }
        }


        holder.checkBox.setOnCheckedChangeListener { _, isChecked ->
            if (item.isChecked != isChecked) {
                item.isChecked = isChecked

                when (item.rowType) {
                    RowType.TopHeader -> {
                        val indexList = mutableListOf<Int>()
                        productList.filter { it.rowType != RowType.TopHeader }.forEach {
                            it.isChecked = isChecked
                            indexList.add(productList.indexOf(it))
                        }
                        indexList.forEach {
                            notifyItemChanged(it)
                        }
                    }
                    RowType.Course -> {
                        val indexList = mutableListOf<Int>()
                        productList.filter { it.rowType == RowType.SubjectRow && it.category == item.category }
                            .forEach {
                                it.isChecked = isChecked
                                indexList.add(productList.indexOf(it))
                            }
                        indexList.forEach {
                            notifyItemChanged(it)
                        }
                        isAllItemsSameStatus() //for header

                    }
                    RowType.SubjectRow -> {
                        isAllItemsSameStatus(item.category) //set prep area accordingly
                        isAllItemsSameStatus() //set top header
                    }
                }
            }
        }

        when (item.rowType) {
            RowType.SubjectRow -> {
                if (holder.checkBox.isChecked)
                    selectedCheckboxes?.add(holder.checkBox.text.toString())
                if (!holder.checkBox.isChecked) {
                    Toast.makeText(context, holder.checkBox.text, Toast.LENGTH_SHORT).show()
                    selectedCheckboxes?.remove(holder.checkBox.text.toString())
                }
            }
        }
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TableViewHolder {
        return TableViewHolder(
            LayoutInflater.from(context).inflate(
                R.layout.rv_trail,
                parent,
                false
            )
        )
    }

    class TableViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        val checkBox: CheckBox = itemView.findViewById(R.id.trailCheckbox)

    }

    override fun getItemCount() = productList.size


    fun setList(profiles: List<RowModel>) {
        productList = profiles
        notifyDataSetChanged()
    }

    private fun isAllItemsSameStatus(cat: String? = null) {

        val row: RowModel
        var isChecked: Boolean = true
        var position: Int = 0

        if (cat != null) {
            val catRow = productList.find { it.rowType == RowType.Course && it.category == cat }
            catRow?.let {
                val subList =
                    productList.filter { it.category == it.category && it.rowType == RowType.SubjectRow }
                isChecked = subList.filter { it.isChecked }.size == subList.size
                position = productList.indexOf(catRow)
            }
            if (catRow == null)
                return
            else
                row = catRow
        } else {
            row = productList[0]
            isChecked =
                productList.filter { it.rowType != RowType.TopHeader && it.isChecked }.size == productList.size - 1
            position = 0
        }

        updateHeader(row, isChecked, position)
    }


    private fun updateHeader(item: RowModel, isChecked: Boolean, position: Int) {
        if (item.isChecked != isChecked) // no need to update if no change
        {
            item.isChecked = isChecked
            notifyItemChanged(position)

        }
    }

    private fun convertDpToPixel(dp: Float, context: Context): Float {
        return dp * (context.resources
            .displayMetrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
    }

    companion object {
        var selectedCheckboxes: MutableList<String>? = null
    }

}

这是我的模型代码:-

data class RowModel (
    val rowType: RowType,
    val subjectName: String,
    val category: String,
    var isChecked: Boolean = true)

enum class RowType(val id : Int) {

    TopHeader(1),
    Course(2),
    SubjectRow(3);

}

这是 activity_trail 布局代码:-

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".CheckboxesActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/trail_rv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <Button
        android:id="@+id/showTextBtn"
        style="@style/ButtonTransparent"
        android:text="@string/save"/>

    <TextView
        android:id="@+id/ShowTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>


</LinearLayout>

问题的逻辑是:-

我正在尝试进行活动,如果:- 1)选中所有课程复选框,则应选中所有其他复选框,反之亦然。

2)选中所有科学按钮,然后应选择所有其他主题按钮,反之亦然。所有其他科目也一样。

3)如果任何课程按钮没有被选中,那么所有课程按钮也不应该被选中。所有科目也一样。

单击 showTextBtn(按钮)后。该应用程序正在崩溃。这是崩溃报告:-

java.lang.NullPointerException
        at com.trail.CheckboxesActivity.onCreate$lambda-0(CheckboxesActivity.kt:45)
        at com.trail.CheckboxesActivity.$r8$lambda$Q7Wv2MEY_mNrpZmgjbfsuGABR0o(Unknown Source:0)
        at com.trail.CheckboxesActivity$$ExternalSyntheticLambda0.onClick(Unknown Source:2)
        at android.view.View.performClick(View.java:8160)
        at android.widget.TextView.performClick(TextView.java:16222)
        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1194)
        at android.view.View.performClickInternal(View.java:8137)
        at android.view.View.access$3700(View.java:888)
        at android.view.View$PerformClick.run(View.java:30236)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:246)
        at android.app.ActivityThread.main(ActivityThread.java:8653)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)

在这里,我试图获取所有选定复选框的文本。在 textView 中显示该文本。其他一切工作正常,但问题仅在于获取选定复选框文本应用程序崩溃的值时。如果可能的话,你能告诉我如何使用字符串数组而不是输入所有这些列表吗?

普拉萨德诉巴加特案

而不是使用:-

var selectedCheckboxes: MutableList<String>? = null

利用:-

var selectedCheckboxes: ArrayList<String> = ArrayList()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用复选框的空指针异常

如何根据收到的值检查复选框

如何检查Android列表中的所有复选框

使用Javascript获取“所有”复选框的值

如何使用jQuery检查所有复选框?

使用jQuery在复选框中检查所有具有特定值的值

如何使用jQuery从复选框组获取检查值

如何检查所有复选框?试图检查所有复选框,测试通过,但在视觉上我看不到它们已被选中

如何检查除禁用复选框之外的所有复选框?

如果所有子复选框都被选中,如何检查父复选框

如何通过单击复选框或文本来检查所有复选框

如何检查除特殊复选框以外的所有复选框?

如何检查所有复选框,甚至是分页隐藏的复选框?

如何检查所有复选框是否都未选中

如何检查所有子复选框

如何使用 jquery/javascript 获取选中复选框的所有值?

如何通过使用jQuery获取所有选定复选框的值?

使用jQuery检查所有更改icheck的复选框

获取所有最近的字段的值,在其中使用serialize动态检查输入复选框

获取所有选中的复选框值

从复选框列表中获取所有值

我如何根据下拉值取消选中所有复选框

如何输出所有复选框的值

从复选框获取空值

当我选中所有复选框时如何选择所有复选框

如何检查多个复选框的值?

如何获取已检查的引导复选框值

我想获取复选框值

如何在jQuery中仅检查所有类别复选框或其他剩余类别复选框