TP Gestion Produits Correctrion 1
TP Gestion Produits Correctrion 1
SQLite est une base de données relationnelle accessible par le langage SQL. SQLite
implémente en
grande partie le standard SQL-92 et des propriétés ACID. Elle est directement intégrée dans
un fichier indépendant de la plateforme.
Vous devez créer une classe utilitaire pour travailler avec la base de données SQLite, cette
classe devrait s'étendre de la classe SQLiteOpenHelper. Il existe deux méthodes importantes
dont vous devez remplacer (override): onCreate() et onUpgrade().
1. Créez la classe DatabaseHelper s'étend à partir de SQLiteOpenHelper.
2. Après avoir étendu votre classe à partir de SQLiteOpenHelper vous devez outrepasser des
deux méthodes onCreate() et onUpgrage()
o onCreate() - C'est là où vous devez écrire créer des instructions de table. C'est ce
qu'on appelle (called) lorsque la base de données est créée.
o onUpgrade() - Cette méthode est appelée lors de la mise à niveau de la base de
données, comme la modification de la structure de la table, l'ajout de contraintes à
la base de données, etc.
DatabaseHelper
public class DatabaseHelper extends SQLiteOpenHelper {
private static DatabaseHelper instance;
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Ajouter un produit"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.411" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Liste de produits"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.415"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Maintenant pour la création de la base de données, nous devons créer une classe java
DatabaseHelper qui herite de SQLiteOpenHelper
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//mise a jour en cas de existance de table produits il va le recréer
db.execSQL("DROP TABLE IF EXISTS produits");
onCreate(db);
}
}
<TextView
android:id="@+id/txtRef"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Ref:" />
<EditText
android:id="@+id/editRef"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" />
<TextView
android:id="@+id/txtDesignation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Designation:" />
<EditText
android:id="@+id/editDesignation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
/>
<TextView
android:id="@+id/txtPrix"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Prix:" />
<EditText
android:id="@+id/editPrix"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" />
<TextView
android:id="@+id/txtQte"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Quantité:" />
<EditText
android:id="@+id/editQte"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" />
<Button
android:id="@+id/btnEnregistere"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enregistrer"
android:onClick="btnEnregisterProduit"/>
</LinearLayout>
import androidx.appcompat.app.AppCompatActivity;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
//recupere la BD en ecriture
SQLiteDatabase
db=DatabaseHelper.getInstance(getApplicationContext()).getWritableDatabase();
//executer la requete
//inserer les values sous forme de tableau de string donc remplacer les ?
// par les elts correspondant dans le tableau de String
String req="INSERT INTO produits(ref,designation,prix,qte)"+
"Values(?,?,?,?)";
db.execSQL(req,new String[]{
txtRef.getText().toString(),
txtDesigantion.getText().toString(),
txtPrix.getText().toString(),
txtQte.getText().toString()
});
}
}
Les donnees sont insérer dans une listview, pour la lecture nous allons utiliser
getReadableDatabase
execSQL retourne int, nbre ligne affectée selon le nbre de ligne inséree….
Ici, la selection c’est un résultat récupérée sous forme de lignes, nous allons utiliser un curseur
en utilisant rawQuery(req, param)
Et puis lecture et parcours des différentes lignes par index de lignes, 0 pour le premier
champ…. Ou bien par nom de colomne getColumnIndex("column1")
SQLiteDatabase db = DatabaseHelper
.getInstance(getApplicationContext())
.getReadableDatabase();
Cursor cursor=db.rawQuery("SELECT * FROM table",null);
while (cursor.moveToNext()){
// cursor.getInt(0)
// cursor.getString(1)
// cursor.getString(cursor.getColumnIndex("column1"));
}
Maintenant dans notre exemple :
Ajoutant une empty activité ListProduitActivity(LinearLayout)
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
import androidx.appcompat.app.AppCompatActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.example.produitdatabase.bean.Produits;
import java.util.ArrayList;
import java.util.List;
//il s'agit ici de notre bean, on peut le mettre dans un package bean
while (cursor.moveToNext()) {
//creer un objet de type produit afin d'y stocker les données
Produits prd=new Produits();
prd.setRef(cursor.getString(1));
prd.setDesignation(cursor.getString(2));
prd.setPrix(cursor.getInt(3));
prd.setQte(cursor.getInt(4));
produits.add(prd);
}
//ajouter produit dans liste
//pour cela utiliser arrayadapter
// ArrayAdapter(contexxt,item,liste)
//l'adapter va supporter les elts de la liste un par un et
// les affecter au item du layout correspondant
//item existant dans android
ArrayAdapter<Produits> adapter= new
ArrayAdapter<Produits>(getApplicationContext(),
android.R.layout.simple_list_item_1,produits);
listview.setAdapter(adapter);
}
}
bean Produits
package com.example.produitdatabase.bean;
public Produits() {
}
afin d’afficher la liste de produits, il faut encore modifier main activité ajouter l’evenement
correspondant et le developper
public void btnListeProduit(View view) {
Intent intent=new Intent(this, ListProduitsActivity.class);
startActivity(intent);
}
<TextView
android:id="@+id/item"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="@color/colorPrimaryDark"
android:textSize="18sp"/>
</LinearLayout>
android:layout_margin="20dp"
Ici on aura deux possibilité pour un pds ou bien le modifier ou le supprimer, la methode
utilisé sera getWritableDatabase
SQLiteDatabase db = DatabaseHelper
.getInstance(getApplicationContext())
.getWritableDatabase();
db.execSQL("UPDATE table SET column1 = ?,column2 = ? WHERE
column_id = ?",
new String[]{"param1","param2","param_id"});
dans notre exemple
l’objectif est de choisir un élément de la liste, lorsqu’on clique dessus, affiche son détail et va
m’orienter vers modification ou suppression
pour ce faire
créer empty activity DeailProduitActivity
et le layout correspondant (LinearLayout) avec deux bouton modifier et supprimer
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".DetailProduitsActivity"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Ref:"/>
<TextView
android:id="@+id/textdetailRef"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:gravity="center"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Designation:"/>
<TextView
android:id="@+id/textdetailDesignation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:gravity="center"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Prix:"/>
<TextView
android:id="@+id/textdetailPrix"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:gravity="center"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Quantite:"/>
<TextView
android:id="@+id/txtdetailqte"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:gravity="center"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Modifier"
android:onClick="btnModifierProduit"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Supprimer"
android:layout_marginLeft="32dp"
android:onClick="btnSupprimerProduit"/>
</LinearLayout>
</LinearLayout>
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.example.produitdatabase.bean.Produits;
import java.util.ArrayList;
import java.util.List;
//il s'agit ici de notre bean, on peut le mettre dans un package bean
while (cursor.moveToNext()) {
//creer un objet de type produit afin d'y stocker les données
Produits prd=new Produits();
prd.setId(cursor.getInt(0));
prd.setRef(cursor.getString(1));
prd.setDesignation(cursor.getString(2));
prd.setPrix(cursor.getInt(3));
prd.setQte(cursor.getInt(4));
produits.add(prd);
}
//ajouter produit dans liste
//pour cela utiliser arrayadapter
// ArrayAdapter(contexxt,item,liste)
//l'adapter va supporter les elts de la liste un par un et
// les affecter au item du layout correspondant
//item existant dans android
// ArrayAdapter<Produits> adapter= new
ArrayAdapter<Produits>(getApplicationContext(),
// android.R.layout.simple_list_item_1,produits);
listview.setAdapter(adapter);
//ajouter l'evenement correspondant au click sur un elts de la liste et
//affihcer le layout detail produits
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long
id) {
Intent intent=new
Intent(getApplicationContext(),DetailProduitsActivity.class);
//icio on va passer des données passer des pramètres
//data,objet liste produits a la position correspondantes
//l'objet que nous devons passer doit etre sérialisable
//pour ce faire il faut implementer la méthode sérialisable
//il suffit que notre bean implements serialisable
//ajouter private id
//toute donnée de l'objet qui peut etre enregistrée doit etre ajoutée
intent.putExtra("data",produits.get(position) );
startActivity(intent);
}
});
}
}
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.example.produitdatabase.bean.Produits;
//
private TextView txtDetailRef,txtDetailDesignation, txtDetailPrix, txtDetailQte;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_produits);
Intent intent=getIntent();
//recuperer produit qui est serialisable
Produits prd=(Produits)intent.getSerializableExtra("data");
//afficher les elts du produit
//relier objet avce le fichier xml
txtDetailDesignation=findViewById(R.id.textdetailDesignation);
txtDetailRef=findViewById(R.id.textdetailRef);
txtDetailPrix=findViewById(R.id.textdetailPrix);
txtDetailQte=findViewById(R.id.textdetailqte);
//affecter valeur aux objets
txtDetailRef.setText(prd.getRef());
txtDetailDesignation.setText(prd.getDesignation());
txtDetailPrix.setText(prd.getPrix()+"Dt");
txtDetailQte.setText(String.valueOf(prd.getQte()));
maintenant pour modifier, envoyer le contrenu vers le formulaire d’insertion et effectuer les
modifications
public void btnModifierProduit(View view) {
Intent intent=new Intent(getApplicationContext(),AjouterProduitActivity.class);
intent.putExtra("data",prd );
startActivity(intent);
}
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import com.example.produitdatabase.bean.Produits;
Intent intent=getIntent();
prd= (Produits) intent.getSerializableExtra("data");
//ici il faut tester le mode modification pd !=null ou ajout pd=null
if (prd!=null)
{
txtRef.setText(prd.getRef());
txtDesigantion.setText(prd.getDesignation());
txtPrix.setText(String.valueOf(prd.getPrix()));
txtQte.setText(String.valueOf(prd.getQte()));
update=true;
}
//recupere la BD en ecriture
SQLiteDatabase db =
DatabaseHelper.getInstance(getApplicationContext()).getWritableDatabase();
//executer la requete
//inserer les values sous forme de tableau de string donc remplacer les ?
// par les elts correspondant dans le tableau de String
//selon update ou ajout
if (update) {
String req = "UPDATE produits SET ref= ?,designation=?,prix=?,qte=? where
id=?";
db.execSQL(req, new String[]{
txtRef.getText().toString(),
txtDesigantion.getText().toString(),
txtPrix.getText().toString(),
txtQte.getText().toString(),
String.valueOf(prd.getId())
});
} else {
String req = "INSERT INTO produits(ref,designation,prix,qte)" +
"Values(?,?,?,?)";
db.execSQL(req, new String[]{
txtRef.getText().toString(),
txtDesigantion.getText().toString(),
txtPrix.getText().toString(),
txtQte.getText().toString()
});
}
//dans l'ajout ajouter appel vers liste pour que vers chaque ajout listepds
Intent intent=new Intent(this, ListProduitsActivity.class);
startActivity(intent);
}
}
Enfin la suppression
Suppression des données
}
});
//creer l'interface
AlertDialog dialog=builder.create();
dialog.show();