Tutoriel : comment créer une base de données SQLite
avec l’Android Studio
L’objectif est de savoir comment créer une BD à l’aide du moteur SQLite avec
l’option CRUD (Create, Read, Update, Delete), dans le but de faciliter la gestion
des étudiants. La base de données doit contenir une table ayant comme
champs ou attributs : nom, pernom, id et note.
Vous allez trouver tous le code java et xml de cette application dont son
interface principale qui ressemble à celle-ci , on proposera de l’amélioration,
voir le résultat à la fin de ce tutoriel.
Code XML de l’interface graphique:
<?xml version="1.0" encoding="utf-8"?>
<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:layout_editor_absoluteY="81dp">
<TextView
android:id="@+id/textView2"
android:layout_width="300dp"
android:layout_height="33dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:text="@string/liste_etudiant"
android:textSize="22dp"
app:layout_constraintBottom_toTopOf="@+id/eTxtNom"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
<EditText
android:id="@+id/eTxtNom"
android:layout_width="278dp"
android:layout_height="45dp"
android:layout_marginStart="8dp"
android:layout_marginTop="50dp"
android:layout_marginEnd="8dp"
android:ems="10"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.911"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/eTxtPrenom"
android:layout_width="273dp"
android:layout_height="0dp"
android:layout_marginStart="80dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="68dp"
android:ems="10"
app:layout_constraintBottom_toTopOf="@+id/eTxtId"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.826"
app:layout_constraintStart_toStartOf="parent" />
<EditText
android:id="@+id/eTxtNote"
android:layout_width="278dp"
android:layout_height="43dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="56dp"
android:ems="10"
app:layout_constraintBottom_toBottomOf="@+id/eTxtId"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toEndOf="@+id/txtVnote" />
<EditText
android:id="@+id/eTxtId"
android:layout_width="278dp"
android:layout_height="43dp"
android:layout_marginStart="8dp"
android:layout_marginTop="116dp"
android:layout_marginEnd="8dp"
android:ems="10"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/eTxtNom" />
<Button
android:id="@+id/butModifier"
android:layout_width="360dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="16dp"
android:onClick="studentHandler"
android:text="@string/but_modifier"
app:layout_constraintBottom_toTopOf="@+id/butSupp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/butAff"
app:layout_constraintVertical_bias="0.49" />
<Button
android:id="@+id/butAdd"
android:layout_width="360dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="24dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:onClick="studentHandler"
android:text="@string/but_ajouter"
app:layout_constraintBottom_toTopOf="@+id/butAff"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/eTxtId"
app:layout_constraintVertical_bias="0.25" />
<Button
android:id="@+id/butAff"
android:layout_width="360dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="130dp"
android:onClick="studentHandler"
android:text="@string/but_afficher"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/butAdd" />
<Button
android:id="@+id/butSupp"
android:layout_width="360dp"
android:layout_height="44dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:text="@string/but_supprimer"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.74"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/eTxtId"
app:layout_constraintVertical_bias="0.90999997" />
<[Link]
android:id="@+id/guideline2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_begin="20dp" />
<TextView
android:id="@+id/txtVnom"
android:layout_width="53dp"
android:layout_height="29dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:text="@string/nom"
android:textSize="15dp"
app:layout_constraintBaseline_toBaselineOf="@+id/eTxtNom"
app:layout_constraintEnd_toStartOf="@+id/eTxtNom"
app:layout_constraintHorizontal_bias="0.344"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="@+id/txtVprenom"
android:layout_width="74dp"
android:layout_height="32dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:text="@string/prenom"
android:textSize="15dp"
app:layout_constraintBaseline_toBaselineOf="@+id/eTxtPrenom"
app:layout_constraintEnd_toStartOf="@+id/eTxtPrenom"
app:layout_constraintHorizontal_bias="0.615"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="@+id/txtVnote"
android:layout_width="55dp"
android:layout_height="26dp"
android:layout_marginStart="20dp"
android:text="@string/note"
android:textSize="15dp"
app:layout_constraintBaseline_toBaselineOf="@+id/eTxtNote"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="@+id/txtVid"
android:layout_width="61dp"
android:layout_height="24dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:text="@string/id"
android:textSize="15dp"
app:layout_constraintBaseline_toBaselineOf="@+id/eTxtId"
app:layout_constraintEnd_toStartOf="@+id/eTxtId"
app:layout_constraintStart_toStartOf="parent" />
</[Link]>
Code XML du fichier strings:
<resources>
<string name="app_name">Studants_DB</string>
<string name="liste_etudiant"> Liste Etudiants</string>
<string name="etudiants">Etudiants</string>
<string name="nom">NOM</string>
<string name="prenom">PRENOM</string>
<string name="note">NOTE</string>
<string name="id">ID</string>
<string name="but_ajouter">Ajouter</string>
<string name="but_afficher">Afficher</string>
<string name="but_modifier">Modifier</string>
<string name="but_supprimer">Supprimer</string>
<string name="but_trouver">Trouver</string>
</resources>
Code java en instanciant la classe SQLiteOpenHelper qui aide à céer une base de données:
package [Link].studants_db;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Student_db";
public static final String TABLE_NAME = "student_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "SURNAME";
public static final String COL_4 = "NOTE";
public DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
[Link]("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY
AUTOINCREMENT,NAME TEXT,SURNAME TEXT,NOTE FLOAT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
[Link]("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name, String surname, String note){
SQLiteDatabase db= [Link]();
ContentValues values=new ContentValues();
[Link](COL_2, name);
[Link](COL_3, surname);
[Link](COL_4, note);
long result=[Link](TABLE_NAME, null, values);
if (result == -1)
return false;
else
return true;
}
//read all data
public Cursor getAllData(){
SQLiteDatabase db= [Link]();
Cursor res=[Link]("select * from "+ TABLE_NAME, null);
return res;
}
//updating data
public boolean updateData(String id, String name, String surname,
String note){
SQLiteDatabase db= [Link]();
ContentValues values=new ContentValues();
[Link](COL_1,id);
[Link](COL_2, name);
[Link](COL_3, surname);
[Link](COL_4, note);
[Link](TABLE_NAME, values,"ID= ?", new String[] {id});
return true;
}
//deleting data
public Integer deleteData(String id){
SQLiteDatabase db=[Link]();
return [Link](TABLE_NAME, "ID=?", new String[] {id});
}
/* public boolean deleteData(int id){
//SQLiteDatabase db =[Link]();
//return [Link](TABLE_NAME, "ID = ?", new String[] {id});
boolean result = false;
String query = "Select*FROM" + TABLE_NAME + "WHERE" + COL_1 + "= '"
+ [Link](id) + "'";
SQLiteDatabase db = [Link]();
Cursor cursor = [Link](query, null);
Student student = new Student();
if ([Link]()) {
[Link]([Link]([Link](0)));
[Link](TABLE_NAME, COL_1 + "=?",
new String[] {
[Link]([Link]())
});
[Link]();
result = true;
}
[Link]();
return result;
}*/
}
Code java de l’activité principale
package [Link].studants_db;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDb;
EditText editName,editSurname,editMarks ,editTextId;
Button btnAddData;
Button btnviewAll;
Button btnDelete;
Button btnviewUpdate;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
myDb = new DatabaseHelper(this);
editName = (EditText)findViewById([Link]);
editSurname = (EditText)findViewById([Link]);
editMarks = (EditText)findViewById([Link]);
editTextId = (EditText)findViewById([Link]);
btnAddData = (Button)findViewById([Link]);
btnviewAll = (Button)findViewById([Link]);
btnviewUpdate= (Button)findViewById([Link]);
btnDelete= (Button)findViewById([Link]);
}
public void studentHandler(View v){
switch ([Link]()){
case [Link]:
boolean isInserted =
[Link]([Link]().toString(),
[Link]().toString(),
[Link]().toString() );
if(isInserted == true)
[Link]([Link],"Data
Inserted",Toast.LENGTH_LONG).show();
else
[Link]([Link],"Data not
Inserted",Toast.LENGTH_LONG).show();
break;
// Editing data
case [Link]:
Cursor res=[Link]();
if([Link]() == 0){
//show message
showMessage("ERROR", "Nothing Found");
return;
}
StringBuffer buffer = new StringBuffer();
while ([Link]()){
[Link]("___________________"+"\n");
[Link]("ID:"+ [Link](0)+"\n");
[Link]("NOM:"+[Link](1)+"\n");
[Link]("PRENOM:"+ [Link](2)+"\n");
[Link]("NOTE:" +[Link](3)+"\n");
//show all data
showMessage("Etudiants", [Link]());
}
break;
//modifing data
case [Link]:
boolean isUpdate =
[Link]([Link]().toString(),
[Link]().toString(),
[Link]().toString(),
[Link]().toString() );
if(isUpdate == true)
[Link]([Link],"Data
modified",Toast.LENGTH_LONG).show();
else
[Link]([Link],"Data not
Modified",Toast.LENGTH_LONG).show();
break;
//deleting data
case [Link]:
Integer deleteRows =
[Link]([Link]().toString());
if(deleteRows>0)
[Link]([Link],"Data
deleted",Toast.LENGTH_LONG).show();
else
[Link]([Link],"Data not
deleted",Toast.LENGTH_LONG).show();
break;
}
}
private void showMessage(String title, String message) {
[Link] builder= new [Link](this);
[Link](true);
[Link](title);
[Link](message);
[Link]();
}
Amélioration de l’interface graphique
En utilisant les styles, les couleurs et les dimensions,
Ajoutons la déclaration des couleurs à utiliser :
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#008577</color>
<color name="colorPrimaryDark">#00574B</color>
<color name="colorAccent">#D81B60</color>
<color name="colortext">#0000ff</color>
<color name="colorButton">#0099ff</color>
</resources>