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

Android中无法创建ShopViewModel实例的问题求助

问题解决:AndroidViewModel实例化失败

错误根源

继承AndroidViewModel的类必须接收Application作为构造参数,而默认的viewModels()调用不会自动传入该参数,导致ViewModelProvider无法完成实例创建。

核心解决方案

在Activity中使用viewModels的重载方法,指定AndroidViewModelFactory来提供Application参数:

val shopViewModel by viewModels<ShopViewModel> {
    AndroidViewModelProvider.AndroidViewModelFactory.getInstance(application)
}

额外优化与检查点

  1. 补全缺失的getJsonDataFromAsset实现
    避免因函数未实现导致的空指针或IO错误,示例实现:

    fun getJsonDataFromAsset(context: Context, fileName: String): String? {
        return try {
            context.assets.open(fileName).bufferedReader().use { it.readText() }
        } catch (ioException: IOException) {
            ioException.printStackTrace()
            null
        }
    }
    
  2. 优化ViewModel数据加载逻辑
    当前同步读取assets文件可能阻塞主线程,建议放到viewModelScope协程中执行:

    class ShopViewModel(application: Application) : AndroidViewModel(application) {
        var items by mutableStateOf(emptyList<ShopItem>())
    
        init {
            viewModelScope.launch {
                val jsonFileString = getJsonDataFromAsset(getApplication(), "Store.json")
                items = ShopItemsRepo.getItems(jsonFileString) ?: emptyList()
            }
        }
    
        fun deleteItem(shopItem: ShopItem){
            items = items.toMutableList().also {
                it.remove(shopItem)
            }
        }
    }
    
  3. 简化Gson解析函数
    无需手动遍历添加元素,直接返回解析结果即可:

    fun shopItems(jsonFileString: String?): List<ShopItem>? {
        jsonFileString ?: return null
        val gson = Gson()
        val listType = object : TypeToken<List<ShopItem>>() {}.type
        return gson.fromJson(jsonFileString, listType)
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 04:43:27