Ce projet présente comment gérer en mode séquentiel une base de données SQL avec une table contenant une liste de personnage avec nom , prénom et date de naissance.

J’ai donnée comme nom à l’application TutoSQL
Android : Gestion d’une base de données SQL en mode séquentiel
- Définition de la base de données et des accès à celle-ci
- 1.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
// The ID is unique and automatically assigned: 1, 2, ...
// The format of birth day is yyyy-mm-dd
class Person(
var individualId: Long,
var name: String,
var firstname: String,
var birth: String,
)
- 2.Base de données
Dans l’application le nom de la base de données est « tutoSql.db »
Nom du fichier : DbOpenHelper.kt
import android.annotation.SuppressLint
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteDatabase.CursorFactory
import android.database.sqlite.SQLiteException
import android.database.sqlite.SQLiteOpenHelper
import android.util.Log
import com.tutosql.data.Common
import com.tutosql.data.Constant
@Suppress("UNCHECKED_CAST")
class DBOpenHelper (
private val context: Context?,
private val name: String?,
private val factory: CursorFactory?,
private val version: Int
) : SQLiteOpenHelper(context, name, factory, version) {
/**
* @goals This class aims to show the constant to use for the DBOpenHelper
*/
override fun onCreate(db: SQLiteDatabase) {
// Create the new database using the SQL string Database_create
db.execSQL(PERSON_CREATE)
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
Log.w(
"DBOpenHelper", ("Version update " + oldVersion
+ " To version " + newVersion
+ ", old data will be destroyed ")
)
// Drop the old database
db.execSQL("DROP TABLE IF EXISTS " + Constant.TABLE_PERSON)
// Create the new one
onCreate(db)
// or do a smartest stuff
}
// Delete the table
fun delAll(context: Context) {
context.deleteDatabase(name)
}
// Select all the rows in the database and order by name
fun selectTab(table: String):Cursor{
val res: Cursor = Common.db!!.rawQuery("SELECT name, firstname, birth FROM $table ORDER BY name", null)
return res
}
// Select the row where name is equal to select and order by firstname
fun selectTabWhere(table: String, select: String): Cursor{
val res: Cursor = Common.db!!.rawQuery("SELECT name, firstname, birth FROM $table WHERE name = \"$select\" ORDER BY firstname", null)
return res
}
// Count the number of rows in the table
@SuppressLint("Recycle")
fun count(table: String): Int{
val res: Cursor = Common.db!!.rawQuery("SELECT (COUNT(*)) FROM $table", null )
res.moveToFirst()
val nb = res.getInt(0)
return nb
}
// Open the database
fun openDB() {
Common.db = try {
Common.dbOpenHelper!!.writableDatabase
} catch (ex: SQLiteException) {
Common.dbOpenHelper!!.readableDatabase
}
}
// Close the database
fun closeDb(){
Common.db?.close()
}
// Create the table
companion object {
/**
* The static string to create the database.
*/
const val PERSON_CREATE = ("create table "
+ Constant.TABLE_PERSON + "(" + Constant.KEY_COL_ID
+ " integer primary key autoincrement, "+ Constant.KEY_NAME + " TEXT, "
+ Constant.KEY_FIRSTNAME + " TEXT, "
+ Constant.KEY_BIRTH + " TEXT) ")
}
}
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 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
- 1.Menu
Gestion des différentes commandes
Fichier menu.xml
<?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>
- 2.Données communes
Fichier Constant.kt
class Constant {
companion object {
// Constant for database
const val DATABASE_VERSION: Int = 1 // Version of database
const val DATABASE_NAME = "tutoSql"
const val TABLE_PERSON: String = "PERSO" // The name of the table
const val KEY_COL_ID: String = "id" // id, mandatory
const val KEY_NAME: String = "name"
const val KEY_FIRSTNAME: String = "firstname"
const val KEY_BIRTH: String = "birth"
}
}
Fichier Common.kt
import android.annotation.SuppressLint
import android.database.sqlite.SQLiteDatabase
import com.tutosql.data.base.DBOpenHelper
class Common {
companion object{
var db: SQLiteDatabase? = null
@SuppressLint("StaticFieldLeak")
var dbOpenHelper: DBOpenHelper? = null
var selectName: String = ""
}
}
- 3.MainActivity
Fichier MainActivity.kt.
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.tutosql.databinding.ActivityMainBinding
import com.tutosql.person.FragmentAllPerson
import com.tutosql.person.FragmentNamePerson
import com.tutosql.person.FragmentNewPerson
import com.tutosql.person.FragmentSelectName
class MainActivity : AppCompatActivity() {
companion object{
val fragmentAllPerson = FragmentAllPerson()
val fragmentNamePerson = FragmentNamePerson()
val fragmentNewPerson = FragmentNewPerson()
val fragmentSelectName = FragmentSelectName()
}
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)
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 -> {
val fragmentManager = (this as FragmentActivity).supportFragmentManager
val frame = fragmentManager.beginTransaction()
frame.replace(R.id.fragment_main, fragmentSelectName)
frame.commit()
}
else -> {
Toast.makeText(this, "No command", Toast.LENGTH_LONG).show()
super.onOptionsItemSelected(item)
}
}
return super.onOptionsItemSelected(item)
}
}
Le programme au lancement affiche si la base de données est non vide la liste des noms présents
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.TutoSql"
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>
- 4.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.content.ContentValues
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 com.tutosql.MainActivity.Companion.fragmentAllPerson
import com.tutosql.R
import com.tutosql.data.Common
import com.tutosql.data.Constant
import com.tutosql.data.model.Person
import com.tutosql.databinding.FragmentNewPersonBinding
class FragmentNewPerson: Fragment() {
private lateinit var binding: FragmentNewPersonBinding
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) {
val contentPerson = ContentValues()
contentPerson.put(Constant.KEY_NAME, person.name)
contentPerson.put(Constant.KEY_FIRSTNAME, person.firstname)
contentPerson.put(Constant.KEY_BIRTH, person.birth)
Common.dbOpenHelper?.openDB()
Common.db?.insert(Constant.TABLE_PERSON, null, contentPerson)
Common.dbOpenHelper?.closeDb()
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
<?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="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: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: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: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="@android:drawable/ic_menu_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="@android:drawable/ic_menu_revert" />
</LinearLayout>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
- 5.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 android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import com.tutosql.data.Common
import com.tutosql.data.Constant
import com.tutosql.data.base.DBOpenHelper
import com.tutosql.data.model.Person
import com.tutosql.databinding.FragmentShowPersonBinding
class FragmentAllPerson: Fragment() {
private lateinit var binding: FragmentShowPersonBinding
private var adapter: OperationListAdapter? = null
var listPersons = mutableListOf<Person>()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
binding = FragmentShowPersonBinding.inflate(inflater, container, false)
Common.dbOpenHelper = DBOpenHelper(
context, Constant.DATABASE_NAME, null,
Constant.DATABASE_VERSION
)
readPersons()
return binding.root
}
// Read all persons in the database
@SuppressLint("Recycle")
private fun readPersons(){
Common.dbOpenHelper?.openDB()
listPersons.clear()
// Count the number of persons in the table
val nbPersons = Common.dbOpenHelper?.count(Constant.TABLE_PERSON)
binding.nbPersons.text = nbPersons.toString()
if(nbPersons == 0) {
Toast.makeText(context, "No person in the database", Toast.LENGTH_LONG).show()
}else{
val res = Common.dbOpenHelper!!.selectTab(Constant.TABLE_PERSON)
res.let {
if (it.moveToFirst()) {
do {
val person = Person(0L, "", "", "")
person.name = res.getString(0)
person.firstname = res.getString(1)
person.birth = res.getString(2)
listPersons.add(person)
} while (res.moveToNext())
}
}
recyclerViewListPerson()
}
Common.dbOpenHelper?.closeDb()
}
@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>
- 6.FragmentSelectName
The fragment permet de sélectionner un nom dans la liste des noms présents dans la base de données.
Fichier FragmentSelectName.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 android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.tutosql.MainActivity
import com.tutosql.R
import com.tutosql.data.Common
import com.tutosql.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 {
Common.selectName = (binding.editTextText.text.toString().trim()).uppercase()
if(Common.selectName.isNotEmpty()) {
val fragmentManager = (activity as FragmentActivity).supportFragmentManager
val frame = fragmentManager.beginTransaction()
frame.replace(R.id.fragment_main, MainActivity.fragmentNamePerson)
frame.commit()
}else{
Toast.makeText(context, "Select name is empty", Toast.LENGTH_LONG).show()
}
}
binding.cancel.setOnClickListener {
Common.selectName = ""
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_name.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="@android:drawable/ic_media_play" />
<ImageView
android:id="@+id/cancel"
android:layout_width="@dimen/iconSize"
android:layout_height="@dimen/iconSize"
android:layout_weight="1"
app:srcCompat="@android:drawable/ic_menu_revert" />
</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.recyclerview.widget.RecyclerView
import com.tutosql.data.Common
import com.tutosql.data.Constant
import com.tutosql.data.model.Person
import com.tutosql.databinding.FragmentShowPersonBinding
class FragmentNamePerson: Fragment() {
private lateinit var binding: FragmentShowPersonBinding
private var adapter: OperationListAdapter? = null
var listPersons = mutableListOf<Person>()
var name: String = ""
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
// Read all persons in the database
private fun readPersons(){
Toast.makeText(context, "Select name : " + Common.selectName, Toast.LENGTH_LONG).show()
Common.dbOpenHelper?.openDB()
listPersons.clear()
var nbPerson = 0
val res = Common.dbOpenHelper!!.selectTabWhere(Constant.TABLE_PERSON, Common.selectName)
res.let {
if (it.moveToFirst()) {
do {
val person = Person(0L, "", "", "")
person.name = res.getString(0)
person.firstname = res.getString(1)
person.birth = res.getString(2)
listPersons.add(person)
nbPerson += 1
} while (res.moveToNext())
}
}
Common.dbOpenHelper?.closeDb()
binding.nbPersons.text = nbPerson.toString()
recyclerViewListPerson()
}
@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
}
}
- 7.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.tutosql.data.model.Person
import com.tutosql.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>
- Aperçu du résultat