Télécharger au format pdf ou txt
Télécharger au format pdf ou txt
Vous êtes sur la page 1sur 21

Developpement Mobile Native SQLite

TP Utilisation de base de données SQLite sous Android


Les Opérations de base: CREATE ;INSERT; SELECT;UPDATE ;DELETE
Exemple Pratique

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;

Hend Ben Ayed Kharrat Page | 1


Developpement Mobile Native SQLite

public static synchronized DatabaseHelper getInstance(Context context){


if(instance==null){
instance=new DatabaseHelper(context);
}
return instance;
}
private DatabaseHelper(Context context) {}
@Override
public void onCreate(SQLiteDatabase db) {}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){}
}

1.Créer un projet et concevoir l'interface


Créez un projet "Empty Activity" pour pratiquer notre exemple Name: Produitdatabase
Commençons par l’interface principale MainActivity.xml

Développer le fichier xml correspondant


<?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"
tools:context=".MainActivity">

<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Ajouter un produit"

Hend Ben Ayed Kharrat Page | 2


Developpement Mobile Native SQLite

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

Avec l’ajout de constructeur, ces deux méthodes onCreate et onUpgrade


package com.example.produitdatabase;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

public class DatabaseHelper extends SQLiteOpenHelper {

//pour ne pas instancier la base de données plusieurs fois


// et si instancier elle retorne celle ouverte
private static DatabaseHelper instance;
//recupere instance, sinon creer nouvelle et l'instancier
public static synchronized DatabaseHelper getInstance(Context context)
{
if (instance==null)
{
instance =new DatabaseHelper(context);
}
return instance;

public DatabaseHelper(Context context) {


super(context, "Produit.db", null, 1);
}

Hend Ben Ayed Kharrat Page | 3


Developpement Mobile Native SQLite

//en cas de modification de la tables, ajout de colonne, ...on incremante la version


@Override
public void onCreate(SQLiteDatabase db) {
//ici on utilise une seule base db
//creation table req SQL
//tjs l’ID est autoincrement et primary key
String req="create table produits("+
"id INTEGER PRIMARY KEY,"+
"ref TEXT,"+
"designation TEXT,"+
"prix INTEGER,"+
"gte INTEGER)";
db.execSQL(req);

@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);
}
}

Maintenant pour tester ceci


Ajouter l’événement correspondant dans l’interface Menu Principal btnAjouterProduit
Et développer la méthode correspondante

public void btnAjouterProduit(View view) {


DatabaseHelper.getInstance(getApplicationContext()).getWritableDatabase();
}

tester la création de la base de données dans ViewTool


WindowsDeviceFileExplorerDataData et chercher la base données correspondante à
notre projet. Puis DataBAse Et le fichier Produits.db que vous aller exporter et l’ouvrir avec
DBEaser, DB Browser..

Donc ici création base de données et Table


Passons maintenant à l’insertion
Insertion des données

Hend Ben Ayed Kharrat Page | 4


Developpement Mobile Native SQLite

Accédons maintenant a notre Helper en mode écriture getWritableDatabase afin de pouvoir


insérer des données. Pour ce faire :
SQLiteDatabase db = DatabaseHelper
.getInstance(getApplicationContext())
.getWritableDatabase();
db.execSQL("INSERT INTO table (column1,column2)VALUES(?,?)",
new String[]{"param1","param2"});
Dans notre application :
Ajouter une empty Activity : AjouterProduitActivity et générer son Layout
Définissons maintenant l’interface d’ajout (LinearLayout) :

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AjouterProduitActivity"
android:orientation="vertical">

<TextView

Hend Ben Ayed Kharrat Page | 5


Developpement Mobile Native SQLite

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" />

Hend Ben Ayed Kharrat Page | 6


Developpement Mobile Native SQLite

<Button
android:id="@+id/btnEnregistere"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enregistrer"
android:onClick="btnEnregisterProduit"/>

</LinearLayout>

Créant maintenant l’événement correspondant


Récupérant donc les editText et developper la fonction Enregistrer produits et y mettre la
requete d’insertion correspondante
package com.example.produitdatabase;

import androidx.appcompat.app.AppCompatActivity;

import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class AjouterProduitActivity extends AppCompatActivity {

private EditText txtRef,txtDesigantion,txtPrix,txtQte;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ajouter_produit);
txtDesigantion=findViewById(R.id.editDesignation);
txtPrix=findViewById(R.id.editPrix);
txtQte=findViewById(R.id.editQte);
txtRef=findViewById(R.id.editRef);

public void btnEnregisterProduit(View view) {

//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()

Hend Ben Ayed Kharrat Page | 7


Developpement Mobile Native SQLite

});

}
}

developper l’intent corrsspondant pour l’appel a notre formulaire


public void btnAjouterProduit(View view) {
//appeler l'activité correspondante
Intent intent=new Intent(this, AjouterProduitActivity.class);
startActivity(intent);

verifier l’ajout correspondant dans la base de données


passons maintenant a la lecture des données insérée : la liste des enregistrements
Selection des données

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)

Hend Ben Ayed Kharrat Page | 8


Developpement Mobile Native SQLite

<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ListProduitsActivity">

<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>

Développeons maintenant la partie Java


Récupérer les données Produits et l’affecter a notre listview
package com.example.produitdatabase;

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;

public class ListProduitsActivity extends AppCompatActivity {

Hend Ben Ayed Kharrat Page | 9


Developpement Mobile Native SQLite

private ListView listview;


//creer une liste de type produits
private List<Produits> produits=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_produits);
listview = findViewById(R.id.listview);
SQLiteDatabase db =
DatabaseHelper.getInstance(getApplicationContext()).getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM produits ", null);
//parcourir données
//ici il faut créer un objet java de type Produit afin d'y recupere les données

//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 class Produits {


private String ref;
private String designation;
private int prix;
private int qte;

public Produits() {
}

Hend Ben Ayed Kharrat Page | 10


Developpement Mobile Native SQLite

public Produits(String ref, String designation, int prix, int qte) {


this.ref = ref;
this.designation = designation;
this.prix = prix;
this.qte = qte;
}

public String getRef() {


return ref;
}

public void setRef(String ref) {


this.ref = ref;
}

public String getDesignation() {


return designation;
}

public void setDesignation(String designation) {


this.designation = designation;
}

public int getPrix() {


return prix;
}

public void setPrix(int prix) {


this.prix = prix;
}

public int getQte() {


return qte;
}

public void setQte(int qte) {


this.qte = qte;
}
}

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);
}

tester maintenant la liste de produits


ok mais l’item choisi par defaut doit etre personnalisé

Hend Ben Ayed Kharrat Page | 11


Developpement Mobile Native SQLite

donc créer un layout pour chaque item produit_item.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/item"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="@color/colorPrimaryDark"
android:textSize="18sp"/>
</LinearLayout>

De plus dans ListProduitsActivity.java


Dans le cas ou le layout possède un seul elts, il est inutile d’instancier le base adapter
// si item un seul elts donc
// ArrayAdapter(contexxt,layout item,item,liste)
ArrayAdapter<Produits> adapter= new ArrayAdapter<Produits>(getApplicationContext(),
R.layout.produits_item,
R.id.item,
produits);

Si on teste dans la liste il va afficher la reference de l’objet dans la mémoire


Pour resoudre le pb
Dans le bean Produits implementer la méthode tostring()
@Override
public String toString() {
return ref + " : " +designation;
}

Et pour avoir de l’espace entre les items

android:layout_margin="20dp"

passons maintenant a l’edition ou mise ajour d’un produit existant


Mise a jour des données

Hend Ben Ayed Kharrat Page | 12


Developpement Mobile Native SQLite

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

<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"

Hend Ben Ayed Kharrat Page | 13


Developpement Mobile Native SQLite

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

Hend Ben Ayed Kharrat Page | 14


Developpement Mobile Native SQLite

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>

Pour le code Java


Modifier notre liste ListeProduitActivity
package com.example.produitdatabase;

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;

public class ListProduitsActivity extends AppCompatActivity {

private ListView listview;


//creer une liste de type produits
private List<Produits> produits=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_produits);
listview = findViewById(R.id.listview);
SQLiteDatabase db =
DatabaseHelper.getInstance(getApplicationContext()).getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM produits ", null);
//parcourir données
//ici il faut créer un objet java de type Produit afin d'y recupere les données

Hend Ben Ayed Kharrat Page | 15


Developpement Mobile Native SQLite

//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);

// si item un seul elts donc


// ArrayAdapter(contexxt,layout item,item,liste)
ArrayAdapter<Produits> adapter= new
ArrayAdapter<Produits>(getApplicationContext(),
R.layout.produits_item,
R.id.item,
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);
}
});

Hend Ben Ayed Kharrat Page | 16


Developpement Mobile Native SQLite

}
}

passons maintennant a détail activity


pour receptionner les parametres passés dans le on create recuperer intent
package com.example.produitdatabase;

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;

public class DetailProduitsActivity extends AppCompatActivity {

//
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()));

public void btnModifierProduit(View view) {


}

public void btnSupprimerProduit(View view) {


}
}

Hend Ben Ayed Kharrat Page | 17


Developpement Mobile Native SQLite

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);
}

maintenant dans ajouter pds dans le oncreate recuperer l’intent


et verifier les donnees
et fixer le mode modifier ou ajouter
package com.example.produitdatabase;

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;

public class AjouterProduitActivity extends AppCompatActivity {

private EditText txtRef,txtDesigantion,txtPrix,txtQte;


private boolean update=false;
Produits prd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ajouter_produit);
txtDesigantion=findViewById(R.id.editDesignation);
txtPrix=findViewById(R.id.editPrix);
txtQte=findViewById(R.id.editQte);
txtRef=findViewById(R.id.editRef);

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;
}

Hend Ben Ayed Kharrat Page | 18


Developpement Mobile Native SQLite

public void btnEnregisterProduit(View view) {

//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

Hend Ben Ayed Kharrat Page | 19


Developpement Mobile Native SQLite

Le mode est getWritableDatabase et la requete delete avec le parametre column id


SQLiteDatabase db = DatabaseHelper
.getInstance(getApplicationContext())
.getWritableDatabase();
db.execSQL("DELETE FROM table WHERE column_id=?",
new String[]{"param_id"});
dans notre exemple :
Supprimer le produit affiché actuel et retourner vers ma liste
Sans oublier de verifier la suppression par un AlertDialog
public void btnSupprimerProduit(View view) {
//verifier la suppression
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setMessage("etes vous sur de vouloir supprimer ce
produit").setTitle("attention");
//deux bouton
builder.setPositiveButton("OUI", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
SQLiteDatabase
db=DatabaseHelper.getInstance(getApplicationContext()).getWritableDatabase();
db.execSQL("DELETE FROM produits WHERE id =? ",
new String[]{String.valueOf(prd.getId())}
);
//après la suppression retourner l'activté de la liste afin d'afficher la liste après
suppression
Intent intent=new Intent(getApplicationContext(),ListProduitsActivity.class);
startActivity(intent);
}
});
builder.setNegativeButton("NON", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {

}
});
//creer l'interface
AlertDialog dialog=builder.create();

Hend Ben Ayed Kharrat Page | 20


Developpement Mobile Native SQLite

dialog.show();

Hend Ben Ayed Kharrat Page | 21

Vous aimerez peut-être aussi