无法创建类的实例 |带有(应用程序:应用程序)参数的 ViewModel

问题描述 投票:0回答:0

我试图从 DetailUserViewModel 传递参数并最终收到错误“无法创建类的实例”,如果我删除参数(应用程序:应用程序),应用程序正在运行。

感谢任何答案,因为它帮助我完成了期末考试。 非常感谢。

这是我的代码块:

DetailUserViewModel

class DetailUserViewModel(application: Application): ViewModel() {

    private val userRepository: UserRepository = UserRepository(application)

    private val _userDetail = MutableLiveData<DetailUserResponse>()
    val userDetail: LiveData<DetailUserResponse> = _userDetail

    private val _listFollows = MutableLiveData<List<Item>>()
    val listFollows: LiveData<List<Item>> = _listFollows

    private val _isLoading = MutableLiveData<Boolean>()
    val isLoading: LiveData<Boolean> = _isLoading

    fun insert(user: User){
        userRepository.insertUser(user)
    }

    fun delete (user: User){
        userRepository.delete(user)
    }

    fun getUserFavoritesById(id: Int): LiveData<List<User>>{
        return userRepository.getUserFavoritesById(id)
    }



    fun setUserDetail(username: String) {
        showLoading(true)
        val client = ApiConfig.getApiService().getDetailUser(username)
        client.enqueue(object : Callback<DetailUserResponse> {
            override fun onResponse(
                call: Call<DetailUserResponse>,
                response: Response<DetailUserResponse>
            ) {
                if (response.isSuccessful) {
                    showLoading(false)
                    val responseBody = response.body()
                    if (responseBody != null) {
                        _userDetail.value = responseBody
                    }
                }
            }

            override fun onFailure(call: Call<DetailUserResponse>, t: Throwable) {
                Log.e("Failure", "${t.message}")
            }
        })
    }

    fun getFollowers(username: String) {
        showLoading(true)
        val client = ApiConfig.getApiService().getFollowers(username)
        client.enqueue(object : Callback<List<Item>> {
            override fun onResponse(call: Call<List<Item>>, response: Response<List<Item>>) {
                if (response.isSuccessful) {
                    showLoading(false)
                    val responseBody = response.body()
                    if (responseBody != null) {
                        _listFollows.value = responseBody
                    }
                }
            }

            override fun onFailure(call: Call<List<Item>>, t: Throwable) {
                Log.e("Failure", "${t.message}")
            }

        })
    }

    fun getFollowing(username: String) {
        showLoading(true)
        val client = ApiConfig.getApiService().getFollowing(username)
        client.enqueue(object : Callback<List<Item>> {
            override fun onResponse(call: Call<List<Item>>, response: Response<List<Item>>) {
                if (response.isSuccessful) {
                    showLoading(false)
                    val responseBody = response.body()
                    if (responseBody != null) {
                        _listFollows.value = responseBody
                    }
                }
            }

            override fun onFailure(call: Call<List<Item>>, t: Throwable) {
                Log.e("Failure", "${t.message}")
            }

        })
    }

    private fun showLoading(b: Boolean) {
        if (b) {
            _isLoading.value = true
        } else {
            _isLoading.value = false
        }
    }

}

DetailUserViewModelFactory

class DetailUserViewModelFactory(private val application: Application): ViewModelProvider.Factory {

    @Suppress("UNCHECKED_CAST")
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(DetailUserViewModel::class.java)) {
            return DetailUserViewModel(application) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class: ${modelClass.name}")
    }
}

DetailUserActivity

class DetailUserActivity : AppCompatActivity() {

    private lateinit var binding: ActivityDetailUserBinding

    private val viewModel by viewModels<DetailUserViewModel> {
        DetailUserViewModelFactory(application)
    }

    companion object {
        var EXTRA_DATA = "extra_data"

        @StringRes
        private val TAB_TITLES = intArrayOf(
            R.string.tab_text_1,
            R.string.tab_text_2
        )
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityDetailUserBinding.inflate(layoutInflater)
        setContentView(binding.root)

        supportActionBar?.elevation = 0f

        val username = intent.getStringExtra(EXTRA_DATA).toString()

        lifecycleScope.launch {
            viewModel.setUserDetail(username.toString())
            viewModel.userDetail.observe(this@DetailUserActivity) { userDetail ->
                dataList(userDetail)
            }
            viewModel.isLoading.observe(this@DetailUserActivity) { isLoading ->
                if (isLoading) {
                    binding.profileDetail.progressBarDetail.visibility = View.VISIBLE
                } else {
                    binding.profileDetail.progressBarDetail.visibility = View.GONE
                }
            }
        }

        val viewPager: ViewPager2 = binding.viewPager
        val tabs: TabLayout = binding.tabs

        val adapter = SectionsPagerAdapter(this)
        adapter.username = username

        viewPager.adapter = adapter

        TabLayoutMediator(tabs, viewPager) { tabs, position ->
            tabs.text = resources.getString(TAB_TITLES[position])
        }.attach()

        binding.btnFavorite.setOnClickListener {
            Toast.makeText(
                this@DetailUserActivity,
                "Ditambahkan ke favorit!",
                Toast.LENGTH_SHORT
            ).show()
            binding.btnFavorite.setImageResource(R.drawable.ic_favorite_clicked)
        }
    }


    private fun dataList(userDetail: DetailUserResponse) {
        binding.apply {
            val tvName = binding.profileDetail.profileName
            if (userDetail.name == null) {
                tvName.text = userDetail.login
            } else {
                tvName.text = userDetail.name
            }
            profileDetail.tvProfileUsername.text = "@${userDetail.login}"
            profileDetail.tvProfileFollower.text = "${userDetail.followers} Followers"
            profileDetail.tvProfileFollowing.text = "${userDetail.following} Following"
            Glide.with(this@DetailUserActivity)
                .load(userDetail.avatarUrl)
                .into(binding.profileDetail.ivProfileDetail)
        }
    }
}

修复Cannot create an instance of class and make it to DetailActivity的错误

java android kotlin viewmodel
© www.soinside.com 2019 - 2024. All rights reserved.