Learning Hilt
is giving me a hard time, so I've decided to ask you for help.
I have an, where I'd like to perform basic cruds
on room database
. I have inserted some data already, and now, I'd like to display it in console, but I can't manage to do it. It just doesn't print anything at all.
DAO
@Dao
interface EmployeeDAO {
@Query("SELECT * FROM employees")
fun getEmployees(): Flow<EmployeeModel>`
}
repository interface
interface EmployeeRepository {
suspend fun getEmployees(): Flow<EmployeeModel>
}
repository implementation
class RepositoryImplementation @Inject constructor(
private val employeeDAO: EmployeeDAO): EmployeeRepository {
override suspend fun getEmployees(): Flow<EmployeeModel> {
return employeeDAO.getEmployees()
}
}
ViewModel
@HiltViewModel
class EmployeeViewModel @Inject constructor(
private val repository: dagger.Lazy<EmployeeRepository>
) : ViewModel() {
suspend fun getEmployees() = viewModelScope.launch {
repository.get().getEmployees().collect{
println("TEST: ${it.name}")
}
}
}
Fragment
@AndroidEntryPoint
class ManageEmployees : Fragment() {
private var _binding: FragmentManageEmployeesBinding? = null
private val mBinding get() = _binding!!
private val mViewModel: EmployeeViewModel by activityViewModels()
@Inject
lateinit var repo: EmployeeRepository
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentManageEmployeesBinding.inflate(inflater, container, false)
val view = mBinding.root
viewLifecycleOwner.lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.CREATED) {
mViewModel.getEmployees()
}
}
return view
}
Repository module
@Module
@InstallIn(SingletonComponent::class)
abstract class RepositoryModule {
@Binds
@Singleton
abstract fun bindRepository(
repositoryImplementation: RepositoryImplementation
): EmployeeRepository
}
Database module
@Module
@InstallIn(SingletonComponent::class)
object DatabaseModule {
@Singleton
@Provides
fun createDatabase(
@ApplicationContext context: Context
) = Room.databaseBuilder(
context,
EmployeeDatabase::class.java,
"employee_database"
).build()
@Singleton
@Provides
fun provideDAO(database: EmployeeDatabase): EmployeeDAO{
return database.getDAO()
}
}
you will have to define getEmployeeDAO() method in database like :
// Tell the database the entries will hold data of this type
@Database( entities = [ItemsYouAreStoringInDB::class],version = PUT_YOUR_DATABASE_VERSION )
abstract class YourDatabase : RoomDatabase()
{
abstract class YourDatabase : RoomDatabase() {
abstract fun getYourDao(): YourDAO
}
}
then provide DAO like this :
@Singleton
@Provides
fun provideYourDao(db: YourDatabase) = db.getEmployeeDAO()