🎇 You can create this project step by step with youtube
🎈 Room
🎈 Menu
🎈 Fragments
🎈 Navigation
🎈 Safe Args
🎈 Parcelize
🎈 Toolbar
🎈 RecyclerView
🎈 viewBinding
🎈 Coroutine
🎈 Mvvm
🎈 View Model -Live Data
@Parcelize
@Entity(tableName = "user_table")
data class User(
@PrimaryKey(autoGenerate = true)
val id:Int,
val firstName:String,
val lastName:String,
val age:Int
):Parcelable
@Dao
interface UserDao {
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun addUser(user: User)
@Update
suspend fun updateUser(user:User)
@Delete
suspend fun deleteUser(user:User)
@Query("DELETE FROM user_table")
suspend fun deleteAllUsers()
@Query("SELECT * FROM user_table ORDER BY id ASC")
fun readAllData(): LiveData<List<User>>
}
@Database(entities = [User::class],version =1,exportSchema = false)
abstract class UserDatabase: RoomDatabase() {
abstract fun userDao():UserDao
companion object{
private var INSTANCE: UserDatabase?= null
fun getDatabase(context: Context):UserDatabase{
val tempInstance = INSTANCE
if(tempInstance != null){
return tempInstance
}
synchronized(this){
val instance = Room.databaseBuilder(
context.applicationContext,
UserDatabase::class.java,
"user_database"
).build()
INSTANCE =instance
return instance
}
}
}
}
class UserRepository(private val userDao: UserDao) {
val readAllData: LiveData<List<User>> = userDao.readAllData()
suspend fun addUser(user: User){
userDao.addUser(user)
}
suspend fun updateUser(user: User){
userDao.updateUser(user)
}
suspend fun deleteUser(user: User){
userDao.deleteUser(user)
}
suspend fun deleteAllUsers(){
userDao.deleteAllUsers()
}
}
The ViewModel's role is to provide data to the UI and survive configuration changes. A ViewModel acts as a communication center between the Repository and the UI
class UserViewModel(application: Application): AndroidViewModel(application) {
val readAllData: LiveData<List<User>>
private val repository: UserRepository
init {
val userDao = UserDatabase.getDatabase(application).userDao()
repository = UserRepository(userDao)
readAllData = repository.readAllData
}
fun addUser(user: User){
viewModelScope.launch ( Dispatchers.IO){
repository.addUser(user)
}
}
fun updateUser(user: User){
viewModelScope.launch(Dispatchers.IO) {
repository.updateUser(user)
}
}
fun deleteUser(user: User){
viewModelScope.launch(Dispatchers.IO) {
repository.deleteUser(user)
}
}
fun deleteAllUsers(){
viewModelScope.launch(Dispatchers.IO) {
repository.deleteAllUsers()
}
}
}