java.lang.IllegalStateException: TextView must not

2019-04-21 07:14发布

问题:

I have the following ViewHolder class for my Recycler View,

inner class ItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        private val dateText = itemView.itemDateSummaryList
        private val systolicVal = itemView.systolicValue
        private val diastolicVal = itemView.diastolicValue

        fun update(listItem: SummaryListItemModel) {
            Log.i(TAG, "Update method called " + listItem.date)
            dateText.text = listItem.date
            systolicVal.text = listItem.sysVal.toInt().toString()
            diastolicVal.text = listItem.diasVal.toInt().toString()
        }

    }

But when I run the app an error comes up at the dateText.text = listItem.date saying,

java.lang.IllegalStateException: dateText must not be null
at *****.******.*****.ui.detailview.bloodpressure.SummaryListAdapter$ItemViewHolder.update(SummaryListAdapter.kt:68)

But the listItem.date is not null I have check with the Log.

回答1:

the error is not about listItem.date, the error says that the dateText textview to which you are trying to set text is null ,

double check you are using the correct textview

Possibilities :
1) you might be using wrong id of textview
2) you may have used wrong file while inflating view.

ctrl + click on itemDateSummaryList and see whether the textview is from he same layout file you have infate or otherwise



回答2:

It's saying your dateText view itself is null not the value listItem.date Verify whether you are rendering it correctly, the itemview has the TextView with the id you are trying to access



回答3:

If you are using fragments: 1. Use a global variable that will hold your layout reference

private var root: View? = null   // create a global variable which will hold your layout 
 override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
            root = inflater.inflate(R.layout.your_layout_file_name, container, false)  // initialize it here
            return root
    }

2. To use any view of your layout which is inside your layout you can use it with (root.) like:

root!!.textView.text="Hello"


回答4:

The same happened to me while using Fragment, I took my code from onCreateView and put it to onViewCreated method, the problem solved.



回答5:

I just had the same issue with my RecyclerView. It had been working for months. After numerous unsuccessful troubleshooting steps, I did a Build > Clean Project and it fixed the issue.