目前我的活动课是这样的:
@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 的步骤。
不要像这样声明 viewModel:
private val noticeScreenViewModel : NoticeScreenViewModel by viewModels()
在您的可组合项中这样做:val noticeScreenViewModel : NoticeScreenViewModel = hiltViewModel()
。