简体   繁体   English

使用Kotlin在Recycler View中显示JSON值

[英]Display JSON value in Recycler View using Kotlin

I am trying to display items in bottom navigation activity using recycler view I am able to display the items but I am not able display the values in the activity using JSON format. 我正在尝试使用回收者视图在底部导航活动中显示项目,我能够显示项目,但无法使用JSON格式显示活动中的值。 I am using OKHTTP method. 我正在使用OKHTTP方法。 The code is working before JSON code. 该代码在JSON代码之前有效。 I am using kotlin in my development. 我在开发中使用kotlin。

[{"name":"Test1","age":"10"},{"name":"Test2","location":"20"}]

I have three layouts in my project activity_main.xml, list_row.xml and fragment_home.xml. 我的项目activity_main.xml,list_row.xml和fragment_home.xml中有三种布局。 Recycler view is in fragment_home.xml and list_row.xml contains two text views. Recycler视图位于fragment_home.xml中,list_row.xml包含两个文本视图。

Below code is working fine but I am not sure how to add the JSON value into the code for display. 下面的代码可以正常工作,但是我不确定如何将JSON值添加到代码中进行显示。 I tried below code and if any one have easiest way to do it then let me know. 我尝试了下面的代码,如果有人有最简单的方法,请告诉我。 Any help is appreciated. 任何帮助表示赞赏。

HomeFragment.kt HomeFragment.kt

class HomeFragment : Fragment() {

    private var adapter:PersonListAdapter?=null
    private var personList:ArrayList<Person>?=null
    private var layoutManager: RecyclerView.LayoutManager?=null


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_home, container, false)
        val recyclerView = view.findViewById<RecyclerView>(R.id.recyclerView)

        personList=ArrayList<Person>()
        layoutManager= LinearLayoutManager(this.context)
        adapter= PersonListAdapter(personList,this.context!!)

        recyclerView.layoutManager=layoutManager
        recyclerView.adapter=adapter
        for (i in 0..16) {
            val person = Person()
            person.name="Hello" + i
            person.age = 20 + i
            personList!!.add(person)

        }
        adapter!!.notifyDataSetChanged()
fetchJSON()
return view

    }

JSON Code: JSON代码:

    private fun fetchJSON()
    {
        val SchoolDetailUrl="https://www.abc.app/"
        println("School URL: $SchoolDetailUrl")
        val request= Request.Builder().url(SchoolsDetailUrl).build()
        val client= OkHttpClient()

        client.newCall(request).enqueue(object : Callback {
            override fun onResponse(call: Call, response: Response) {
                val body=response?.body()?.string()

                val gson=GsonBuilder().create()

                val Schoollist=gson.fromJson(body,Array<Person>::class.java)

             //       recyclerView.adapter=PersonDetailAdapter(Schoollist)

                println("Testing School Detail $body")
            }
            override fun onFailure(call: Call, e: IOException) {
                println("Failed to Execute the Request")
            }
        })
    }

}

PersonListAdapter: PersonListAdapter:

class PersonListAdapter(private val list: ArrayList<Person>,
                        private val context: Context)
    : RecyclerView.Adapter<PersonListAdapter.ViewHolder>() {
    override fun getItemCount(): Int {
        return list.size

    }

    override fun onCreateViewHolder(parent: ViewGroup?, position: Int): ViewHolder {
                   val view = LayoutInflater.from(context).inflate(R.layout.list_row, parent, false)

        return ViewHolder(view)


    }

    override fun onBindViewHolder(holder: ViewHolder?, position: Int) {

        holder?.bindItem(list[position])


    }


     inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
         fun bindItem(person: Person) {
             var name: TextView = itemView.findViewById(R.id.name) as TextView
             var age: TextView = itemView.findViewById(R.id.age) as TextView

             name.text = person.name
             age.text = person.age.toString()



             itemView.setOnClickListener {


                 Toast.makeText(context, name.text, Toast.LENGTH_LONG ).show()
             }

         }

    }


}

So What you need is to call the person details API for each click on the person item. 因此,您需要为人员项目上的每次单击调用人员详细信息API。 Currently the 目前

PersonListAdapter(psersonList: ArrayList<Person>,context Context)

has 2 arguments change that to pass another argument the `fetchJson` Function itself

PersonListAdapter(context Context,psersonList: ArrayList<Person>, fetchJson: (string) -> Unit)

In the fetch JSON I think another view is shown with person details that you have to do, 在获取JSON中,我认为显示了另一个视图,其中包含您必须执行的人员详细信息,

NOTE: Normally the context will be the first argument and also In the fetchJSON function if you inflate another view that contains the details then change the function name to some meaning full one like ShowDetails() 注意:通常,上下文将是第一个参数,并且在fetchJSON函数中,如果您膨胀另一个包含详细信息的视图,则将函数名称更改为某些含义完整的名称,例如ShowDetails()

You code has some problems, but your main one is the way your Adapter uses data. 您的代码有一些问题,但是您的主要问题是适配器使用数据的方式。

    personList=ArrayList<Person>()
    adapter= PersonListAdapter(personList,this.context!!)
    [...]
    adapter!!.notifyDataSetChanged()

When you're adding items to the list: 将项目添加到列表中时:

for (i in 0..16) {
    val person = Person()
    person.name="Hello" + i
    person.age = 20 + i
    personList!!.add(person)
}

What you're actually doing is adding to the local list personList , not to private val list: ArrayList<Person> of you're adapter. 您实际上所做的是添加到本地列表personList ,而不是private val list: ArrayList<Person>您的适配器的private val list: ArrayList<Person> That's why you get no data to display. 因此,您无法显示任何数据。

Instead you should add methods like add(person: Person) to your adapter, and let it add to its private val list instead. 相反,您应该在适配器中添加诸如add(person: Person)类的方法,并将其添加到其private val list Keep the data in the Adapter, not your view ;) 将数据保存在适配器中,而不是您的视图中;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM