StepCount
@Entity(tableName = "stepcount", foreignKeys = [ForeignKey(entity = Users::class, parentColumns = ["userId"], childColumns = ["userId"], onDelete = CASCADE)])
data class StepCount (
@PrimaryKey(autoGenerate = true)
val id: Int = 0,
val userId: Int,
val date: String,
val hour: Int,
var steps: Int = 0
)
StepCountDao
@Dao
interface StepCountDao {
@Query("SELECT * FROM stepcount")
fun getAllStepTable(): LiveData
}
StepCountRepository
class StepCountRepository(private val dao: StepCountDao) {
fun getAllStepsTable() : LiveData {
return dao.getAllStepTable()
}
}
Счетчик шагов ViewModelFactory
class StepCountViewModelFactory(
private val repository: StepCountRepository,
private val application: Application): ViewModelProvider.Factory {
override fun create(modelClass: Class): T {
if(modelClass.isAssignableFrom(StepCountViewModel::class.java)) {
return StepCountViewModel(repository, application) as T
}
throw IllegalArgumentException("Unknown View Model Class")
}
}
StepCountViewModel
class StepCountViewModel(private val repository: StepCountRepository, application: Application) : AndroidViewModel(application), Observable {
private var _allStepsTable = MutableLiveData()
val allStepsTable : LiveData
get() = _allStepsTable
fun getAllStepsTable() {
viewModelScope.launch {
_allStepsTable.postValue(repository.getAllStepsTable().value)
}
}
}
DayFragment
class DayFragment : Fragment() {
private lateinit var stepCountViewModel: StepCountViewModel
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val application = requireNotNull(this.activity).application
val dao = UsersDatabase.getInstance(application).stepCountDao()
val repository = StepCountRepository(dao)
val factory = StepCountViewModelFactory(repository, application)
stepCountViewModel = ViewModelProvider(this, factory).get(StepCountViewModel::class.java)
val prefs = application.getSharedPreferences("prefs", Context.MODE_PRIVATE)
val userId = prefs.getInt("userId", -1)
Log.d("userId", userId.toString())
stepCountViewModel.allStepsTable.observe(viewLifecycleOwner, Observer { allStepsTable ->
if (allStepsTable !== null)
Log.i("DAYFRAG_obs_all_steps", allStepsTable.toString())
})
stepCountViewModel.getAllStepsTable()
}
Подробнее здесь: https://stackoverflow.com/questions/760 ... otlin-room
Мобильная версия