Dans ce tutoriel nous allons voir la gestion d’une base de données SQL à partir de la librairie ROOM.

- Ajouter les librairies ROOM dans le projet :
[libraries]
androidx-room-common = { group = "androidx.room", name = "room-common", version.ref = "roomCommon" }
androidx-room-ktx = { group = "androidx.room", name = "room-ktx", version.ref = "roomKtx" }
androidx-room-runtime = { group = "androidx.room", name = "room-runtime", version.ref = "roomKtx"}
androidx-room-compiler = { group = "androidx.room", name = "room-compiler", version.ref = "roomCompiler"}
[plugins]
kotlin-parcelize = { id = "org.jetbrains.kotlin.plugin.parcelize", version.ref = "parcelize"}
- Définition du modèle :
Chaque modèle doit obligatoirement comporter une clef primaire unique qui permet de rendre unique chaque ligne de la table.
Il existe un modèle par table
Non du fichier : Person.kt
import android.os.Parcelable
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import kotlinx.parcelize.Parcelize
// The ID is unique and automatically assigned: 1, 2, ...
// The format of birth day is yyyy-mm-dd
@Entity(tableName = "person")
@Parcelize
data class Person(
@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") var individualId: Long,
@ColumnInfo(name = "name") var name: String,
@ColumnInfo(name = "firstname") var firstname: String,
@ColumnInfo(name = "birth") var birth: String
):Parcelable
- Organisation autonome décentralisée (DAO)
Pour chaque table définir les différentes conditions d’accès en lecture, écriture, mise à jour et suppression.
La définition de l’accès à la table se fait sous la forme d’une requête à la base de données SQL.
Ce fichier fait appel au modèle défini précédemment
Nom du fichier : DaoPerson.kt
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import kotlinx.coroutines.flow.Flow
import com.tutoroom.data.model.Person
@Dao
interface DaoPerson {
// select all persons
@Query("SELECT * FROM person ORDER BY name")
fun getAllPersons(): Flow<List<Person>>
// Select persons with the same name 'name' and range by firstname
@Query("SELECT * FROM person WHERE name IS :name ORDER BY firstname")
fun getSelect(name: String): LiveData<List<Person>>
// Select persons with the name start with 'name'
@Query("SELECT * FROM person WHERE name LIKE :name ORDER BY name")
fun getNameStart(name:String): LiveData<List<Person>>
// Insert new person
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun addPerson(person: Person)
// Update person
@Update
suspend fun updatePerson(person: Person)
// Delete all the name in the database
@Query("DELETE FROM person")
suspend fun delete()
}
- Dépôt (REPOSITORY)
Ce fichier fait appel au modèle ainsi qu’au fichier DAO
Nom du fichier : RepositoryPerson.kt
import androidx.annotation.WorkerThread
import androidx.lifecycle.LiveData
import kotlinx.coroutines.flow.Flow
import com.tutoroom.data.dao.DaoPerson
import com.tutoroom.data.model.Person
class RepositoryPerson(
private val daoPerson: DaoPerson
) {
val getAllPersons: Flow<List<Person>> = daoPerson.getAllPersons()
fun getSelect(name: String): LiveData<List<Person>> =
daoPerson.getSelect(name)
fun getNameStart(name:String): LiveData<List<Person>> =
daoPerson.getNameStart(name)
@WorkerThread
suspend fun insert(person: Person){
daoPerson.addPerson(person)
}
@WorkerThread
suspend fun update(person: Person) {
daoPerson.updatePerson(person)
}
@WorkerThread
suspend fun delete(){
daoPerson.delete()
}
companion object {
@Volatile
private var INSTANCE: RepositoryPerson? = null
fun getRepositoryPerson(daoPerson: DaoPerson): RepositoryPerson {
return INSTANCE
?: synchronized(this) {
val instance = RepositoryPerson(daoPerson)
INSTANCE = instance
return instance
}
}
}
}
- Modèle de vue (viewmodel)
Ce fichier fait appel au modèle ainsi qu’au fichier de dépôt
Nom du fichier : ViewmodelPerson.kt
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.asLiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import com.tutoroom.data.model.Person
import com.tutoroom.data.repository.RepositoryPerson
class ViewmodelPerson(private val repositoryPerson: RepositoryPerson) : ViewModel() {
val getAllPersons: LiveData<List<Person>> = repositoryPerson.getAllPersons.asLiveData()
fun getSelect(name: String): LiveData<List<Person>> =
repositoryPerson.getSelect(name)
fun getPersonStart(name: String): LiveData<List<Person>> =
repositoryPerson.getNameStart(name)
fun insert(person: Person) = viewModelScope.launch {
repositoryPerson.insert(person)
}
fun update(person: Person) = viewModelScope.launch {
repositoryPerson.update(person)
}
fun delete() = viewModelScope.launch {
repositoryPerson.delete()
}
}
- Injection
Ce fichier fait appel à la définition de la base de données qui est défini ci-dessous ainsi qu’au fichier de dépôt
Nom du fichier : Injection.kt
import android.content.Context
import com.tutoroom.data.base.DatabaseSql
import com.tutoroom.data.repository.RepositoryPerson
object Injection {
fun providesRepositoryPerson(context: Context): RepositoryPerson {
val database = DatabaseSql.getDatabase(context)
return RepositoryPerson.getRepositoryPerson(database.daoPerson())
}
}
- « Viewmodel factory »
Ce fichier fait appel au fichier de dépôt et au modèle de vue
Nom du fichier : ViewmodelFactory
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.tutoroom.data.repository.RepositoryPerson
import com.tutoroom.data.viewmodel.ViewmodelPerson
@Suppress("UNCHECKED_CAST")
class ViewmodelFactory(
private val repositoryPerson: RepositoryPerson
) : ViewModelProvider.Factory{
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return when {
modelClass.isAssignableFrom(ViewmodelPerson::class.java) -> ViewmodelPerson(repositoryPerson) as T
else -> throw kotlin.Exception("Unknown ViewModel class")
}
}
}
- Base de données
Ce fichier fait appel au fichier DAO et au modèle
Dans l’application le nom de la base de données est « tutoRoom.db »
Nom du fichier : Database.sql
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.tutoroom.data.dao.DaoPerson
import com.tutoroom.data.model.Person
@Database(entities = [Person::class],
version = 1,
exportSchema = false)
abstract class DatabaseSql: RoomDatabase() {
// DAO
abstract fun daoPerson(): DaoPerson
companion object {
@Volatile
private var INSTANCE: DatabaseSql? = null
fun getDatabase(context: Context): DatabaseSql {
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
DatabaseSql::class.java,
"tutoRoom.db"
).build()
INSTANCE = instance
instance
}
}
}
}
La base de donnée est prête à être utilisée.
- Utilisation de la base de données
Sous android studio, une fois l’application lancée sous émulateur et la base de données activée, sont contenu est visualisable grâce au pictogramme et le fichier est stocké sur l’appareil dans le répertoire data → data → « nom de l’application » → databases
Les différentes commandes sont gérées à partir de fragments
- MainActivity
Fichier MainActivity.kt.
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.activityViewModels
import com.tutoroom.MainActivity.Companion.fragmentAllPerson
import com.tutoroom.R
import com.tutoroom.data.injection.Injection
import com.tutoroom.data.injection.ViewmodelFactory
import com.tutoroom.data.model.Person
import com.tutoroom.data.viewmodel.ViewmodelPerson
import com.tutoroom.databinding.FragmentNewPersonBinding
class FragmentNewPerson: Fragment() {
private lateinit var binding: FragmentNewPersonBinding
val viewmodelPerson: ViewmodelPerson by activityViewModels {
ViewmodelFactory(
Injection.providesRepositoryPerson(requireContext()),
)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
binding = FragmentNewPersonBinding.inflate(inflater, container, false)
binding.save.setOnClickListener {
savePerson()
}
binding.cancel.setOnClickListener {
returnToShow()
}
return binding.root
}
// if name, firstname and birthday is initialise the information are save in the database
private fun savePerson(){
var flag = true
val person = Person(0L, "", "", "")
if(binding.name.text.toString().isNotEmpty()){
person.name = (binding.name.text.toString().trim()).uppercase()
}else{
Toast.makeText(activity, "Name is empty", Toast.LENGTH_LONG).show()
flag = false
}
if(binding.firstname.text.toString().isNotEmpty()){
person.firstname = (binding.firstname.text.toString().trim()).uppercase()
}else{
Toast.makeText(activity, "Firstname is empty", Toast.LENGTH_LONG).show()
flag = false
}
if(binding.birthday.text.toString().isNotEmpty()){
person.birth = binding.birthday.text.toString().trim()
}else{
Toast.makeText(activity, "Birthday is empty", Toast.LENGTH_LONG).show()
flag = false
}
if(flag) {
viewmodelPerson.insert(person)
returnToShow()
}
}
// Return without save the information
private fun returnToShow(){
val fragmentManager = (activity as FragmentActivity).supportFragmentManager
val frame = fragmentManager.beginTransaction()
frame.replace(R.id.fragment_main, fragmentAllPerson)
frame.commit()
}
}
Le programme au lancement affiche si la base de données est non vide la liste des noms présents
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentActivity
import com.tutoroom.databinding.ActivityMainBinding
import com.tutoroom.person.FragmentAllPerson
import com.tutoroom.person.FragmentNamePerson
import com.tutoroom.person.FragmentNewPerson
import com.tutoroom.person.FragmentSelectName
class MainActivity : AppCompatActivity() {
companion object{
val fragmentAllPerson = FragmentAllPerson()
val fragmentNamePerson = FragmentNamePerson()
val fragmentNewPerson = FragmentNewPerson()
val fragmentSelectName = FragmentSelectName()
var name = ""
}
private lateinit var binding: ActivityMainBinding
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.toolbar.inflateMenu(R.menu.menu)
setSupportActionBar(binding.toolbar)
// Show the list of persons
val fragmentManager = (this as FragmentActivity).supportFragmentManager
val frame = fragmentManager.beginTransaction()
frame.replace(R.id.fragment_main, fragmentAllPerson)
frame.commit()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu,menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle item selection.
when (item.itemId) {
R.id.menuNewPerson -> {
val fragmentManager = (this as FragmentActivity).supportFragmentManager
val frame = fragmentManager.beginTransaction()
frame.replace(R.id.fragment_main, fragmentNewPerson)
frame.commit()
}
R.id.menuSelectAll -> {
val fragmentManager = (this as FragmentActivity).supportFragmentManager
val frame = fragmentManager.beginTransaction()
frame.replace(R.id.fragment_main, fragmentAllPerson)
frame.commit()
}
R.id.menuSelectName -> {
name = ""
val fragmentManager = (this as FragmentActivity).supportFragmentManager
val frame = fragmentManager.beginTransaction()
frame.replace(R.id.fragment_main, fragmentSelectName)
frame.commit()
}
R.id.menuExit -> {
exitProcess(0)
}
else -> {
Toast.makeText(this, "No command", Toast.LENGTH_LONG).show()
super.onOptionsItemSelected(item)
}
}
return super.onOptionsItemSelected(item)
}
}
Fichier layout activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@drawable/toolbar"
android:elevation="4dp"
android:theme="@style/Base.Theme.TutoRoom"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:titleTextColor="@color/white">
</androidx.appcompat.widget.Toolbar>
<FrameLayout
android:id="@+id/fragment_main"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:layout_weight="0.80">
</FrameLayout>
</LinearLayout>
- FragmentNewPerson
Dans ce fragment il est demandé le nom, le prénom et la date de naissance du personnage à ajouter dans la base de données. Après validation, la liste des noms présents dans la base de données est affichée.
Fichier FragmentNewPerson.kt
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.activityViewModels
import com.tutoroom.MainActivity.Companion.fragmentAllPerson
import com.tutoroom.R
import com.tutoroom.data.injection.Injection
import com.tutoroom.data.injection.ViewmodelFactory
import com.tutoroom.data.model.Person
import com.tutoroom.data.viewmodel.ViewmodelPerson
import com.tutoroom.databinding.FragmentNewPersonBinding
class FragmentNewPerson: Fragment() {
private lateinit var binding: FragmentNewPersonBinding
val viewmodelPerson: ViewmodelPerson by activityViewModels {
ViewmodelFactory(
Injection.providesRepositoryPerson(requireContext()),
)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
binding = FragmentNewPersonBinding.inflate(inflater, container, false)
binding.save.setOnClickListener {
savePerson()
}
binding.cancel.setOnClickListener {
returnToShow()
}
return binding.root
}
// if name, firstname and birthday is initialise the information are save in the database
private fun savePerson(){
var flag = true
val person = Person(0L, "", "", "")
if(binding.name.text.toString().isNotEmpty()){
person.name = (binding.name.text.toString().trim()).uppercase()
}else{
Toast.makeText(activity, "Name is empty", Toast.LENGTH_LONG).show()
flag = false
}
if(binding.firstname.text.toString().isNotEmpty()){
person.firstname = (binding.firstname.text.toString().trim()).uppercase()
}else{
Toast.makeText(activity, "Firstname is empty", Toast.LENGTH_LONG).show()
flag = false
}
if(binding.birthday.text.toString().isNotEmpty()){
person.birth = binding.birthday.text.toString().trim()
}else{
Toast.makeText(activity, "Birthday is empty", Toast.LENGTH_LONG).show()
flag = false
}
if(flag) {
viewmodelPerson.insert(person)
returnToShow()
}
}
// Return without save the information
private fun returnToShow(){
val fragmentManager = (activity as FragmentActivity).supportFragmentManager
val frame = fragmentManager.beginTransaction()
frame.replace(R.id.fragment_main, fragmentAllPerson)
frame.commit()
}
}
Fichier layout fragment_new_person.xml
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="5dp"
android:orientation="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:orientation="horizontal"
tools:ignore="UselessParent">
<TextView
android:id="@+id/textView6"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="@string/name"
android:textColor="@color/black"
android:textSize="@dimen/textSize" />
<EditText
android:id="@+id/name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:autofillHints=""
android:background="@color/teal_200"
android:ems="10"
android:inputType="text"
android:text="@string/name"
android:textAllCaps="true"
android:textColor="@color/black"
android:textSize="@dimen/textSize"
tools:ignore="LabelFor" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:orientation="horizontal"
tools:ignore="UselessParent">
<TextView
android:id="@+id/textView7"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="@string/firstname"
android:textColor="@color/black"
android:textSize="@dimen/textSize" />
<EditText
android:id="@+id/firstname"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:autofillHints=""
android:background="@color/teal_200"
android:ems="10"
android:inputType="text"
android:text="@string/firstname"
android:textAllCaps="true"
android:textColor="@color/black"
android:textSize="@dimen/textSize"
tools:ignore="LabelFor" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:orientation="horizontal"
tools:ignore="UselessParent">
<TextView
android:id="@+id/textView8"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="@string/birthday_yyyy_mm_dd"
android:textColor="@color/black"
android:textSize="@dimen/textSize" />
<EditText
android:id="@+id/birthday"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:autofillHints=""
android:background="@color/teal_200"
android:ems="10"
android:inputType="text"
android:text="@string/birthday"
android:textColor="@color/black"
android:textSize="@dimen/textSize"
tools:ignore="LabelFor" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:orientation="horizontal"
tools:ignore="UselessParent">
<ImageView
android:id="@+id/save"
android:layout_width="@dimen/iconSize"
android:layout_height="@dimen/iconSize"
android:layout_weight="0.5"
app:srcCompat="@drawable/save" />
<ImageView
android:id="@+id/cancel"
android:layout_width="@dimen/iconSize"
android:layout_height="@dimen/iconSize"
android:layout_marginBottom="5dp"
android:layout_weight="1"
app:srcCompat="@drawable/cancel" />
</LinearLayout>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
- FragmentAllPerson
The fragment affiche la liste des personnes présentes dans la base de données
Fichier FragmentAllPerson.kt.
Ce fragment fait appel à un recyclerview pour afficher la liste des personnes
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.RecyclerView
import com.tutoroom.data.injection.Injection
import com.tutoroom.data.injection.ViewmodelFactory
import com.tutoroom.data.model.Person
import com.tutoroom.data.viewmodel.ViewmodelPerson
import com.tutoroom.databinding.FragmentShowPersonBinding
class FragmentAllPerson: Fragment() {
private lateinit var binding: FragmentShowPersonBinding
private var adapter: OperationListAdapter? = null
var listPersons = mutableListOf<Person>()
val viewmodelPerson: ViewmodelPerson by activityViewModels {
ViewmodelFactory(
Injection.providesRepositoryPerson(requireContext()),
)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
binding = FragmentShowPersonBinding.inflate(inflater, container, false)
readPersons()
return binding.root
}
// Read all persons in the database
private fun readPersons(){
viewmodelPerson.getAllPersons.observe(viewLifecycleOwner) { houses ->
houses?.let {
if (it.isNotEmpty()) {
binding.nbPersons.text = it.size.toString()
listPersons = it as MutableList<Person>
recyclerViewListPerson()
} else {
binding.nbPersons.text = "0"
}
}
}
}
@SuppressLint("DefaultLocale")
private fun recyclerViewListPerson() {
// Initialize the adapter and set it to the RecyclerView.
adapter = OperationListAdapter()
// Getting the recyclerview by its id binding
val recyclerView: RecyclerView = binding.recyclerView
// Setting the Adapter with the recyclerview
adapter?.submitList(listPersons)
recyclerView.adapter = adapter
}
}
Fichier fragment_show_person.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="5dp"
android:layout_marginBottom="5dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
tools:ignore="UselessParent">
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="@string/number_of_persons"
android:textColor="@color/black"
android:textStyle="bold" />
<TextView
android:id="@+id/nb_persons"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="@string/zero"
android:textColor="@color/black"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/textView2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.3"
android:gravity="center"
android:text="@string/name"
android:textAlignment="center"
android:textStyle="bold" />
<TextView
android:id="@+id/textView3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.4"
android:gravity="center"
android:text="@string/firstname"
android:textAlignment="center"
android:textStyle="bold" />
<TextView
android:id="@+id/textView4"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.3"
android:gravity="center"
android:text="@string/birthday"
android:textAlignment="center"
android:textStyle="bold" />
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="4dp"
android:background="#FF909090" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:clipToPadding="false"
android:scrollbars="vertical"
app:layoutManager="LinearLayoutManager" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
- FragmentSelectPerson
The fragment permet de sélectionner un nom dans la liste des noms présents dans la base de données.
Fichier FragmentSelectPerson.xt : demande le nom de la personne à sélectionner
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.tutoroom.MainActivity
import com.tutoroom.R
import com.tutoroom.databinding.FragmentSelectNameBinding
class FragmentSelectName : Fragment() {
private lateinit var binding: FragmentSelectNameBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
binding = FragmentSelectNameBinding.inflate(inflater, container, false)
binding.save.setOnClickListener {
MainActivity.name = (binding.editTextText.text.toString().trim()).uppercase()
val fragmentManager = (activity as FragmentActivity).supportFragmentManager
val frame = fragmentManager.beginTransaction()
frame.replace(R.id.fragment_main, MainActivity.fragmentNamePerson)
frame.commit()
}
binding.cancel.setOnClickListener {
MainActivity.name = ""
val fragmentManager = (activity as FragmentActivity).supportFragmentManager
val frame = fragmentManager.beginTransaction()
frame.replace(R.id.fragment_main, MainActivity.fragmentAllPerson)
frame.commit()
}
return binding.root
}
}
Fichier fragment_select_person.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="5dp"
android:layout_marginBottom="5dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.52"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="UselessLeaf">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="5dp"
android:layout_weight="1"
android:text="@string/name"
android:textSize="@dimen/textSize"
android:textStyle="bold" />
<EditText
android:id="@+id/editTextText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="5dp"
android:layout_weight="1"
android:background="#FFEB3B"
android:ems="10"
android:inputType="text"
android:textSize="@dimen/textSize" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="@+id/save"
android:layout_width="@dimen/iconSize"
android:layout_height="@dimen/iconSize"
android:layout_weight="1"
app:srcCompat="@drawable/save" />
<ImageView
android:id="@+id/cancel"
android:layout_width="@dimen/iconSize"
android:layout_height="@dimen/iconSize"
android:layout_weight="1"
app:srcCompat="@drawable/cancel" />
</LinearLayout>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Fichier FragmentNamePerson.kt : Affichage de la liste des personnes portants le nom sélectionner
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.RecyclerView
import com.tutoroom.MainActivity
import com.tutoroom.data.injection.Injection
import com.tutoroom.data.injection.ViewmodelFactory
import com.tutoroom.data.model.Person
import com.tutoroom.data.viewmodel.ViewmodelPerson
import com.tutoroom.databinding.FragmentShowPersonBinding
class FragmentNamePerson: Fragment() {
private lateinit var binding: FragmentShowPersonBinding
private var adapter: OperationListAdapter? = null
var listPersons = mutableListOf<Person>()
var name: String = ""
val viewmodelPerson: ViewmodelPerson by activityViewModels {
ViewmodelFactory(
Injection.providesRepositoryPerson(requireContext()),
)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
binding = FragmentShowPersonBinding.inflate(inflater, container, false)
readPersons()
return binding.root
}
// Read all persons in the database
private fun readPersons(){
Toast.makeText(context, "Select name : " + MainActivity.name, Toast.LENGTH_LONG).show()
viewmodelPerson.getSelect(MainActivity.name).observe(viewLifecycleOwner) { houses ->
houses?.let {
if (it.isNotEmpty()) {
binding.nbPersons.text = it.size.toString()
listPersons = it as MutableList<Person>
recyclerViewListPerson()
} else {
binding.nbPersons.text = "0"
}
}
}
}
@SuppressLint("DefaultLocale")
private fun recyclerViewListPerson() {
// Initialize the adapter and set it to the RecyclerView.
adapter = OperationListAdapter()
// Getting the recyclerview by its id binding
val recyclerView: RecyclerView = binding.recyclerView
// Setting the Adapter with the recyclerview
adapter?.submitList(listPersons)
recyclerView.adapter = adapter
}
}
- Affichage de la liste des personnes
Fichier OperationListAdapter.kt
import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.tutoroom.data.model.Person
import com.tutoroom.databinding.FragmentPersonItemBinding
class OperationListAdapter :
ListAdapter<Person, OperationListAdapter.OperationViewHolder>(OperationDiffCallback) {
private lateinit var context: Context
/////////////////////////////////////////////////////////////////////////////////////////////////
// Adapter parts
/////////////////////////////////////////////////////////////////////////////////////////////////
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OperationViewHolder {
context = parent.context
return OperationViewHolder(
FragmentPersonItemBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
@RequiresApi(Build.VERSION_CODES.O)
@SuppressLint("NotifyDataSetChanged", "ResourceAsColor")
override fun onBindViewHolder(holder: OperationViewHolder, position: Int) {
holder.bind(getItem(position), context)
}
companion object {
private val OperationDiffCallback = object : DiffUtil.ItemCallback<Person>() {
override fun areItemsTheSame(oldItem: Person, newItem: Person): Boolean {
return (
oldItem.individualId == newItem.individualId ||
oldItem.name == newItem.name ||
oldItem.firstname == newItem.firstname ||
oldItem.birth == newItem.birth
)
}
override fun areContentsTheSame(oldItem: Person, newItem: Person): Boolean {
// return oldItem == newItem
return true
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////
// ViewHolder Parts
/////////////////////////////////////////////////////////////////////////////////////////////////
class OperationViewHolder(private var binding: FragmentPersonItemBinding) :
RecyclerView.ViewHolder(binding.root) {
private lateinit var context: Context
@RequiresApi(Build.VERSION_CODES.O)
@SuppressLint("SetTextI18n", "DefaultLocale")
fun bind(person: Person, context: Context) {
this.context = context
binding.name.setText(person.name)
binding.firstname.setText(person.firstname)
binding.birth.setText(person.birth)
}
}
}
Fichier fragment_person_item.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<EditText
android:id="@+id/name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.3"
android:autofillHints=""
android:ems="10"
android:inputType="text"
android:text="@string/name"
tools:ignore="LabelFor,VisualLintTextFieldSize" />
<EditText
android:id="@+id/firstname"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.3"
android:autofillHints=""
android:ems="10"
android:inputType="text"
android:text="@string/firstname"
tools:ignore="LabelFor,VisualLintTextFieldSize" />
<EditText
android:id="@+id/birth"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.3"
android:autofillHints=""
android:ems="10"
android:inputType="text"
android:text="@string/birthday"
tools:ignore="LabelFor,VisualLintTextFieldSize" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
- Menu
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/menuNewPerson"
android:title="@string/newP"
android:visible="true"
app:showAsAction="never" />
<item
android:id="@+id/menuSelectAll"
android:title="@string/selectAll"
android:visible="true"
app:showAsAction="never" />
<item
android:id="@+id/menuSelectName"
android:title="@string/selectName"
android:visible="true"
app:showAsAction="never" />
<item
android:id="@+id/menuExit"
android:title="@string/menuExit"
android:visible="true"
app:showAsAction="never" />
</menu>
- Aperçu du résultat.