Skip to content

sumeyraozugur/RoomSample

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

19 Commits
 
 
 
 
 
 

Repository files navigation

πŸŽƒ Room Sample πŸŽ†

πŸŽ‡ You can create this project step by step with youtube

Content

🎈 Room
🎈 Menu
🎈 Fragments
🎈 Navigation
🎈 Safe Args
🎈 Parcelize
🎈 Toolbar
🎈 RecyclerView
🎈 viewBinding
🎈 Coroutine
🎈 Mvvm
🎈 View Model -Live Data
⚠️⚠️ Search View is added

πŸ‘» Entity

Represent a table within the database. Room creates a table for each class that has @Entity annotation, the fields in the class correspond to columns in the table. Therefore, the entity classes tend to be small model classes that do not contain any logic
@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

DAOs are responsible for defining the methods that access the database. This is place where we write our queries
@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

Contains the database holder and serves as the main access point for the underlying connection to your app's data
@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
            }
        }

    }
}

πŸ‘Ύ Repository

A repository class abstracts access to multiple data sources. The repository is not part of the Architecture. Components libraries, but is a suggested best practice for code separation and architecture.
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()
    }

}

πŸ€– ViewModel

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()
        }
    }
    
}

🧑 Output 🧑

output