androidautocompleteautocompletetextviewcustom-arrayadapter

AutoComplete does not return desired string


I am new in Kotlin programming. In my android app, I have an array adapter of "addressInfo" objects - objects with data about a place.

class addressInfo
(
var displayName : String,
var latitude : String,
var longitude : String,
var osmType : String,
var osmId : String,
var osmClass : String
)

Following is the code for adapter:

class AutoSuggestAdapter(context: Context, @LayoutRes private val layoutResource: Int) :
ArrayAdapter<addressInfo>(context, layoutResource), Filterable {
private val mlistData: MutableList<addressInfo>
private val TAG = "Adapter"

fun setData(list: List<addressInfo>?) {
    mlistData.clear()
    mlistData.addAll(list!!)
}

override fun getCount(): Int {
    return mlistData.size
}

@Nullable
override fun getItem(position: Int): addressInfo {
    return mlistData[position]
}

/**
 * Used to Return the full object directly from adapter.
 *
 * @param position
 * @return
 */
fun getObject(position: Int): addressInfo {
    return mlistData[position]
}

override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
    val view: TextView = convertView as TextView? ?: LayoutInflater.from(context).inflate(layoutResource, parent, false) as TextView
    var r = mlistData[position].displayName
    view.text = r
    return view
}

init {
    mlistData = ArrayList()
}
}

The suggestions are shown correctly, but choosing one of them returns some wrong text (not the suggestion itself, probably some inner id of the addressInfo object). Screenshot

What I wish to get returned is the displayName string. How to fix this?


Solution

  • I managed to set the desired string inside onItemClickListener method:

    autoCompleteTextView.onItemClickListener =
        OnItemClickListener { parent, view, position, id ->
                autoCompleteTextView.setText(autoSuggestAdapter!!.getObject(position).displayName)
        }