尝试创建 ViewModel 时无法创建类错误的实例

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

目前我的活动课是这样的:

@AndroidEntryPoint
class FamiliarActivity : AppCompatActivity() {

    private val noticeScreenViewModel : NoticeScreenViewModel by viewModels()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            FamiliarTheme {
                val navController = rememberNavController()
                val currentBackStack by navController.currentBackStackEntryAsState()
                val currentDestination = currentBackStack?.destination
                val currentScreen =
                    familiarScreens.find { it.route == currentDestination?.route } ?: Settings

                FamiliarNavHost(
                    noticesViewModel = noticeScreenViewModel,
                    navController = navController,
                    modifier = Modifier.padding()
                )
            }
        }
    }
}

NoticeScreenViewModel 看起来像这样:

@HiltViewModel
class NoticeScreenViewModel @Inject internal constructor(
    private val noticeRepository: NoticeRepository
) : ViewModel(){
    val notices: List<Notice> = noticeRepository.getNotices()

}

NoticeRepository 看起来像这样:

class NoticeRepository @Inject constructor(
    private val noticeDao: NoticeDao
) {

        fun createNotice(notice: Notice) {
            noticeDao.insert(notice)
        }

        fun removeNotice(notice: Notice) {
            noticeDao.delete(notice)
        }

        fun getNotices() = noticeDao.getNotices()

        companion object {

            // For Singleton instantiation
            @Volatile private var instance: NoticeRepository? = null

            fun getInstance(noticeDao: NoticeDao) =
                instance ?: synchronized(this) {
                    instance ?: NoticeRepository(noticeDao).also { instance = it }
                }
        }
}

NoticeDao 看起来像这样:

@Dao
interface NoticeDao {
    @Query("SELECT * FROM notice")
    fun getNotices(): List<Notice>

    @Insert
    fun insertAll(vararg notices: Notice)

    @Insert
    fun insert(notice: Notice)

    @Delete
    fun delete(notice: Notice)

}

而且它永远不会起作用。每次,应用程序都会在 ViewModel 初始化时崩溃。是的,我已经尝试了在类似帖子中找到的所有内容。我错过了什么?

我已经多次重新制作了所有这些类,但从未完成创建 viewModel 的步骤。

android android-jetpack-compose android-room viewmodel dagger-hilt
1个回答
0
投票

不要像这样声明 viewModel:

private val noticeScreenViewModel : NoticeScreenViewModel by viewModels()
在您的可组合项中这样做:
val noticeScreenViewModel : NoticeScreenViewModel = hiltViewModel()

© www.soinside.com 2019 - 2024. All rights reserved.