在 kotlin 中从 json 加载 imageurl 时出错

Error loading imageurl from json in kotlin

我目前正在尝试构建一个 Android 应用程序。我目前正在学习本教程: https://www.javatpoint.com/kotlin-android-custom-listview

但与教程中的示例不同,我从 json 文件中获取图像 url。 它确实从我的 JSON 文件中读取了正确的图像 url。但是我得到这个错误:

    java.lang.NumberFormatException: For input string: "R.drawable.firstimage"

这张图片确实存在于我的 android 项目中。当我在 imageview 中加载硬编码时,它会起作用。 这是我认为应该包含问题的代码部分:

主 kotlin 文件:

    val v = inflater.inflate(R.layout.fragment_producten, container, false)
    val json_text = v.findViewById<ListView>(R.id.json_listp)
    var json : String? = null
    var arr = arrayListOf<String>()
    var fam = arrayListOf<String>()
    var img = arrayListOf<Int>()


    try {
        val pro: InputStream = context?.assets!!.open("products.json")
        json = pro.bufferedReader().use { it.readText()}

        var jsonarr = JSONArray(json)

        for (i in 0..jsonarr.length()-1)
        {
            var jsonobject = jsonarr.getJSONObject(i)
            arr.add(jsonobject.getString("name"))
            fam.add("type")
            img.add(jsonobject.getString("image").toInt())
        }
        val product_adapter = MyProductAdapter(requireActivity(), arr, fam, img)
        json_text.adapter = product_adapter
    }
    catch (e : IOException) {

    }
    return v

这是product_adapter class:

class MyProductAdapter(
private val context: Activity,
private val title: ArrayList<String>,
private val description: ArrayList<String>,
private val imgid: ArrayList<Int>)
: ArrayAdapter<String>(context, R.layout.row_producten, title) {

override fun getView(position: Int, view: View?, parent: ViewGroup): View {
    val inflater = context.layoutInflater
    val rowView = inflater.inflate(R.layout.row_producten, null, true)

    val titleText = rowView.findViewById(R.id.mainrowtitle) as TextView
    val imageView = rowView.findViewById(R.id.productview) as ImageView
    val subtitleText = rowView.findViewById(R.id.rowdescrition) as TextView

    titleText.text = title[position]
    imageView.setImageResource(imgid[position])
    subtitleText.text = description[position]

    return rowView
}
}

我真的希望有人能发现问题

您在 JSON 响应中使用 R.drawable.firstimage(字符串),然后尝试 toInt() 它,因此 NumberFormatException.

您需要获取可绘制对象的名称(例如 firstimage),并在构建 img 时从资源中获取 int ID,使用类似:

val resourceId = context.resources.getIdentifier("firstimage", "drawable", context.packageName)

确保您只传递可绘制对象的名称,而不是前面的 R.drawable.