I have a little problem I couldn't solve. I've searched and I tried a lot of things, Unfortunately no results. Getview is causing an error
The line causnig an error is this one below in ArrayAdapter:
val tvCopiedText:TextView = view!!.findViewById(R.id.tv_copiedText)
Here is the code:
ArrayAdapter
class MyArrayAdapter: ArrayAdapter<CopiedText> {
constructor(context: Context, resource:Int, copiedTexts: List<CopiedText>) : super(context, resource, copiedTexts) {
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
var view: View? = null
val copiedText:CopiedText = getItem(position)
if (convertView == null){
view = LayoutInflater.from(context).inflate(R.layout.item_layout, parent, false)
}
val tvCopiedText:TextView = view!!.findViewById<TextView>(R.id.tv_copiedText)
val tvTime:TextView = view.findViewById<TextView>(R.id.tv_time)
//val tvCopiedText = retView!!.findViewById<TextView>(R.id.tv_copiedText)
//val tvCopiedText = retView!!.findViewById<TextView>(R.id.tv_copiedText)
tvCopiedText.text = copiedText.ctText
tvTime.text = copiedText.ctTime.toString()
return view
}
}
Adapter in MainActivity:
ctAdapter = MyArrayAdapter(this, R.layout.item_layout, listCopiedText)
myListView.adapter = ctAdapter
item_layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:paddingBottom="8dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="8dp"
>
<TextView
android:id="@+id/tv_copiedText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="14sp"
tools:text="Here will be the copied Text" />
<TextView
android:id="@+id/tv_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp"
tools:text="Time"/>
The reason why you are getting a null pointer is because you are not assigning the view
variable to anything in case convertView
is not null. Change this code
var view: View? = null
val copiedText:CopiedText = getItem(position)
if (convertView == null){
view = LayoutInflater.from(context).inflate(R.layout.item_layout, parent, false)
}
to
var view: View? = convertView
val copiedText:CopiedText = getItem(position)
if (view == null){
view = LayoutInflater.from(context).inflate(R.layout.item_layout, parent, false)
}