我尝试使用Hilt将天气存储库注入到我的视图模型中,但得到以下错误消息:
WeatherRepository不能在没有@ Provides注解的方法的情况下提供。
公共抽象静态类SingletonC实现WeatherApplication_GeneratedInjector
Weather DAO:
@Dao
interface WeatherDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertWeatherItem(weatherItem: WeatherItem)
@Query("DELETE FROM WEATHERITEM WHERE cityName = :cityName")
suspend fun deleteWeatherItem(cityName: String)
@Query("SELECT * FROM WEATHERITEM WHERE cityId = :id")
fun getWeatherItem(id: Int): Flow<WeatherItem>
@Query("SELECT * FROM WEATHERITEM")
fun getAllWeatherItems(): Flow<List<WeatherItem>>
}
字符串
天气仓库:
class WeatherRepository(private val weatherDao: WeatherDao) {
suspend fun insertWeatherItem(weatherItem: WeatherItem) = weatherDao.insertWeatherItem(weatherItem)
suspend fun deleteWeatherItem(cityName: String) = weatherDao.deleteWeatherItem(cityName)
fun getWeatherItem(id: Int): Flow<WeatherItem> = weatherDao.getWeatherItem(id)
fun getAllWeatherItems(): Flow<List<WeatherItem>> = weatherDao.getAllWeatherItems()
}
型
天气数据库:
@Database(entities = [WeatherItem::class] ,version = 1)
abstract class WeatherDatabase :RoomDatabase(){
abstract fun weatherDao(): WeatherDao
}
型
天气模块:
@Module
@InstallIn(ActivityComponent::class)
object WeatherModule {
@Provides
@Singleton
fun provideDatabase(@ApplicationContext context: Context): WeatherDatabase {
return Room.databaseBuilder(
context,
WeatherDatabase::class.java,
"WeatherDatabase")
.fallbackToDestructiveMigration()
.build()
}
@Provides
@Singleton
fun provideWeatherDao(weatherDatabase: WeatherDatabase): WeatherDao {
return weatherDatabase.weatherDao()
}
@Provides
@Singleton
fun provideWeatherRepository(weatherDao: WeatherDao): WeatherRepository {
return WeatherRepository(weatherDao)
}
}
型
天气视图模型:
@HiltViewModel
class WeatherViewModel @Inject constructor(
private val weatherRepository: WeatherRepository,
) : ViewModel()
型
主要活动:
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val viewModel: WeatherViewModel by viewModels()
setContent {
WindSpellTheme(darkTheme = darkTheme) {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
MainScreen(viewModel) {
}
}
}
}
}
}
型
适用范围:
@HiltAndroidApp
class WeatherApplication: Application()
型
版本2.47
备注
当导航到 Find usages 时,显示存在对注入对象的引用:x1c 0d1x
1条答案
按热度按时间dl5txlt91#
请尝试从
class WeatherRepository @Inject constructor(private val weatherDao: WeatherDao)
中删除@Inject constructor
,因为您已经在WeatherModule
中拥有它。现在它应该工作。
**P.S.**如果你以后决定让
WeatherRepository
成为一个接口,比如WeatherRepositoryImpl
,你可以这样做:字符串
然后,在一些
Module
中,它是一个 * 接口 * 或 * 抽象类 *:型