You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio(Kotlin)加密货币App Spinner无法加载API数据求助

问题排查与修复方案

你的Spinner无数据显示的核心原因是API数据解析失败+语法错误,导致Adapter未正确绑定数据,以下是具体问题和修复步骤:

1. JSON解析方法笔误

代码中cryptoObject.get3Double("supply")是拼写错误,正确方法名应为getDouble。这个错误会直接抛出异常,导致循环中断,cryptoList始终为空,Spinner自然没有数据。

2. Supply字段类型溢出风险

Coincap API返回的supply是高精度数值(部分币种supply达数十亿级别),直接转Int会触发数值溢出,建议改用Long类型存储。

3. OnItemSelectedListener语法错误

Kotlin中创建匿名内部类的正确语法是object : AdapterView.OnItemSelectedListener,原代码this :的写法会编译报错,导致选择事件无法绑定。


修复后的完整代码

import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Spinner
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.android.volley.Request
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import org.json.JSONObject

data class CryptoInfo(
    val name: String,
    val symbol: String,
    val supply: Long, // 改为Long避免数值溢出
    val priceUSD: Double,
    val percentChange24h: Double
)

class MainActivity : AppCompatActivity() {
    private val cryptoList = ArrayList<CryptoInfo>()

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

    private fun fetchDataFromAPI() {
        val requestQueue = Volley.newRequestQueue(this)
        val url = "https://api.coincap.io/v2/assets"

        val jsonObjectRequest = JsonObjectRequest(Request.Method.GET, url, null,
            { response ->
                val jsonArray = response.getJSONArray("data")
                for (i in 0 until jsonArray.length()) {
                    val cryptoObject = jsonArray.getJSONObject(i)
                    val name = cryptoObject.getString("name")
                    val symbol = cryptoObject.getString("symbol")
                    // 修复get3Double拼写错误,转Long类型
                    val supply = cryptoObject.getDouble("supply").toLong()
                    val priceUSD = cryptoObject.getDouble("priceUsd")
                    val percentChange24h = cryptoObject.getDouble("changePercent24Hr")

                    cryptoList.add(CryptoInfo(name, symbol, supply, priceUSD, percentChange24h))
                }

                // 绑定Spinner数据
                val spinner = findViewById<Spinner>(R.id.spinner)
                val cryptoNames = cryptoList.map { it.name }
                val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, cryptoNames)
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
                spinner.adapter = adapter

                // 修复选择事件绑定语法
                spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                    override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                        updateCryptoInfo(cryptoList[position])
                    }

                    override fun onNothingSelected(parent: AdapterView<*>?) {}
                }
            },
            { error ->
                android.util.Log.e("API_ERROR", "Error fetching data: ${error.message}")
            })

        requestQueue.add(jsonObjectRequest)
    }

    private fun updateCryptoInfo(cryptoInfo: CryptoInfo) {
        findViewById<TextView>(R.id.cryptoNameTextView).text = cryptoInfo.name
        findViewById<TextView>(R.id.symbolTextView).text = cryptoInfo.symbol
        findViewById<TextView>(R.id.supplyTextView).text = cryptoInfo.supply.toString()
        findViewById<TextView>(R.id.priceTextView).text = String.format("%.2f", cryptoInfo.priceUSD)
        findViewById<TextView>(R.id.percentChangeTextView).text = String.format("%.2f%%", cryptoInfo.percentChange24h)
    }
}

额外建议

  • 确认AndroidManifest.xml中已添加网络权限:<uses-permission android:name="android.permission.INTERNET"/>
  • 可在API回调中添加日志Log.d("CryptoData", "Fetched ${cryptoList.size} items"),验证数据是否正确获取
  • 对supply字段添加千分位格式化,提升大数显示的可读性

内容的提问来源于stack exchange,提问作者hashslingingslasher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 11:01:03