Advertisement

Responsive Advertisement

Use Dependency injection using Dagger-hilt use kapt or ksp in Your Project PART2

 6) In Activity of fragment class you have to add annotations below :

@HiltViewModel
class RoomViewModel @Inject constructor(private val repo: RoomRepo) : ViewModel() {}
fun getUserList() {
viewModelScope.launch {
withContext(Dispatchers.IO) {
try {
_userlist.postValue(repo.getAllUsers())
} catch (e: Exception) {
Log.e(
"roshan",
"getUserList from viewmodel: ${e.localizedMessage ?: "error in somewhere"}"
)
}
}
}
}

7) In Repository file you have to only inject

class RoomRepo @Inject constructor(private val dao: UserDao) {)
suspend fun insertUser(user: User) {
try {
dao.insertUser(user)
} catch (e: Exception) {
Log.e("roshan", "insertUser: ${e.localizedMessage ?: "something went woring"}")
}
}

8) For dao setup create entitiy first which is model class

@Entity
data class User(
@PrimaryKey(autoGenerate = true) val id:Int=0,
val name:String?=null,
val email:String,
val password:String,
val companyName:String?=null
)

@Entity
data class ProductList(
@PrimaryKey(autoGenerate = true)
val id:Int=0,
val pName:String,
val pQty:Int,
val pRate:Int,
val pImage:String?=null,
var manualQty:Int=0
)


9) Create database class 

@Database(entities = [User::class,ProductList::class], version = 1, exportSchema = false)
@TypeConverters(Converters::class)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao():UserDao

}


10) Add converters like this if it needs

class Converters {
@TypeConverter
fun fromUri(uri: Uri?): String? {
return uri?.toString()
}

@TypeConverter
fun toUri(uriString: String?): Uri? {
return uriString?.let { Uri.parse(it) }
}
}


11) Some Query related to database

@Dao
interface UserDao {
@Insert
suspend fun insertUser(user: User)

@Query("SELECT * FROM User")
suspend fun getAllUsers(): List<User>

@Query("SELECT * FROM ProductList")
suspend fun getAllProducts(): List<ProductList>

@Insert
suspend fun inserProduct(productList: ProductList)

@Query("SELECT EXISTS (SELECT 1 FROM User WHERE email = :email LIMIT 1)")
suspend fun isUserExists(email: String): Boolean

@Query("SELECT EXISTS (SELECT 1 FROM User WHERE email = :email AND password = :password LIMIT 1)")
suspend fun isUserFound(email: String, password: String): Boolean


}

Now call accordingly your view & functioanlity .,......

Post a Comment

0 Comments