0

столкнулся с такой, проблемой надо передать ArrayList из объекта(там содержится только String) в Adapter. Код который у меня:

Adapter:

class AdapterC (val countryList: Collection<Countries>): RecyclerView.Adapter<AdapterC.ViewHolder>() {
override fun onCreateViewHolder(p0: ViewGroup, p1: Int): ViewHolder {
    val v = LayoutInflater.from(p0?.context).inflate(R.layout.country_list,p0,false)
    return  ViewHolder(v)
}

override fun getItemCount(): Int {
    return countryList.size
}

override fun onBindViewHolder(p0: ViewHolder, p1: Int) {
    val country : Countries=countryList.toTypedArray()[p1]
    p0?.textViewName.text=country.name
}


class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
    val textViewName= itemView.findViewById(R.id.TextViewCountry) as TextView
}}

MainActivity:

class MainActivity : AppCompatActivity() {
val adapter= AdapterC(Collections.emptyList<Countries>())

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val recyclerView= findViewById(R.id.recyclerView) as RecyclerView
    recyclerView.layoutManager=LinearLayoutManager(this,LinearLayout.VERTICAL,false)

    recyclerView.adapter=adapter
}

И функция где пытаюсь записать значение которые получил в Adapter:

  private  fun handleJson(jsonString:String?){
    val jsonResult = JSONObject(jsonString)
    val resultobject=jsonResult.getJSONObject("results")
    val list =ArrayList<Countries>()
    var iter=resultobject.keys()

    iter.forEach {
        var country = resultobject.getJSONObject(it)
        var name = country.optString("name")
        var item=Countries(name)
        list.add(item)
    }
    //   adapter.countryList.submitList(list)  <-- Подсвечивает красным SubmitList
    //   adapter.countryList.clear() <-- Подсвечивает красным clear
    //   adapter.countryList.addAll(list) <-- Подсвечивает красным addList
    adapter.notifyDataSetChanged()
}
0

1 ответ 1

0

Нашел решение проблемы. В Adaptere поменять значение

class AdapterC (val countryList: Collection<Countries>): RecyclerView.Adapter<AdapterC.ViewHolder>() {
override fun onCreateViewHolder(p0: ViewGroup, p1: Int): ViewHolder {

На

class AdapterC (val countryList: ArrayList<Countries>): RecyclerView.Adapter<AdapterC.ViewHolder>() {
    override fun onCreateViewHolder(p0: ViewGroup, p1: Int): ViewHolder {

В MainActivity

val adapter= AdapterC(Collections.emptyList<Countries>())

на

val adapter= AdapterC(arrayListOf<Countries>())

И тогда это заработает

adapter.countryList.clear()
adapter.countryList.addAll(list)

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.