1. ENSAF Pr. A. JEGHAL Programmation mobile M : IOSEM 2020/2021
1
TP4 : Persistance des données
Création et manipulation d’une base de données SQLite
L’objectif c’est de savoir créer et manipuler une base de données SQLite. A cet égard on veut
créer une base de données pour stocker et afficher les services de la direction de l’ENSAF.
Pour ce faire en suivant les étapes suivantes :
1. Créer un projet nommé MyDB,
2. Créer une base de données à l’aide de la classe SQLiteOpenHelper (par exemple
MySQLiteHelepr.java),
3. Ajouter une classe qui contient les données à stocker et à afficher dans l’interface
(exemple, Direction.java) ,
4. Créer une classe (par exemple EnsaFDataSource.java) pour gérer les sources de
données et avoir l’accès à ces données,
5. Changer le fichier layout main.xml par exemple,
6. Changer le fichier de l’activity de telle sorte à afficher les données en utilisant une
ListView .
Créer une base de données à l’aide de la classe SQLiteOpenHelper (par exemple
MySQLiteHelepr),
package com.example.tp_sqlit;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class MySQLiteHelper extends SQLiteOpenHelper {
public static final String TABLE_ENSAF = "ensaf";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_DIRECTION = "direction";
private static final String DATABASE_NAME = "ensaf.db";
private static final int DATABASE_VERSION = 1;
// Database creation sql statement
private static final String DATABASE_CREATE = "create table "
+ TABLE_ENSAF + "(" + COLUMN_ID
+ " integer primary key autoincrement, " + COLUMN_DIRECTION
+ " text not null);";
//implement a constructer with 3 parameters
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase database) {
2. ENSAF Pr. A. JEGHAL Programmation mobile M : IOSEM 2020/2021
2
database.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(MySQLiteHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ENSAF);
onCreate(db);
}
}
Ajouter une classe qui contient les données à stocker et à afficher dans l’interface
(exemple, Direction),
package com.example.tp_sqlit;
public class Direction {
private long id;
private String direction;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getDirection() {
return direction;
}
public void setDirection(String comment) {
this.direction = comment;
}
// Will be used by the ArrayAdapter in the ListView
@Override
public String toString() {
return direction;
}
}
Créer une classe (par exemple EnsafDataSource) pour gérer les sources données et avoir
l’accès à ces données,
package com.example.tp_sqlit;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
public class EnsafDataSource {
3. ENSAF Pr. A. JEGHAL Programmation mobile M : IOSEM 2020/2021
3
// Database fields
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] allColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_DIRECTION };
public EnsafDataSource(Context context) {
dbHelper = new MySQLiteHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public Direction createDirection(String direction) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_DIRECTION, direction);
long insertId = database.insert(MySQLiteHelper.TABLE_ENSAF, null,
values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_ENSAF,
allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
Direction newDirection = cursorToDirection(cursor);
cursor.close();
return newDirection;
}
public void deleteDirection(Direction direction) {
long id = direction.getId();
System.out.println("direction_service deleted with id: " + id);
database.delete(MySQLiteHelper.TABLE_ENSAF, MySQLiteHelper.COLUMN_ID
+ " = " + id, null);
}
public List<Direction> getAllComments() {
List<Direction> ensaf = new ArrayList<Direction>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_ENSAF,
allColumns, null, null, null, null, null);
// On place le curseur au début en vérifiant qu’il contient des résultats.
cursor.moveToFirst();//Déplace le curseur à la première position pour
lire les données de la première ligne.
while (!cursor.isAfterLast()) {
Direction direction = cursorToDirection(cursor);
ensaf.add(direction);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return ensaf;
}
private Direction cursorToDirection(Cursor cursor) {
Direction direction = new Direction();
4. ENSAF Pr. A. JEGHAL Programmation mobile M : IOSEM 2020/2021
4
direction.setId(cursor.getLong(0));
direction.setDirection(cursor.getString(1));
return direction;
}
}
Changer le fichier layout activity_main.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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:orientation="vertical"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:showIn="@layout/activity_main" tools:context=".MainActivity">
<LinearLayout
android:id="@+id/group"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="@+id/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add New"
android:onClick="onClick"/>
<Button
android:id="@+id/delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete First"
android:onClick="onClick"/>
</LinearLayout>
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
Changer le fichier de l’activity de telle sorte à afficher les données en utilisant une
ListView.
package com.example.tp_sqlit;
import android.app.ListActivity;
import android.database.SQLException;
import android.os.Bundle;
5. ENSAF Pr. A. JEGHAL Programmation mobile M : IOSEM 2020/2021
5
import android.view.View;
import android.widget.ArrayAdapter;
import java.util.List;
import java.util.Random;
public class MainActivity extends ListActivity {
private EnsafDataSource datasource;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
datasource = new EnsafDataSource(this);
try {
datasource.open();
} catch (SQLException e) {
e.printStackTrace();
}
List<Direction> values = datasource.getAllComments();
// use the SimpleCursorAdapter to show the
// elements in a ListView
ArrayAdapter<Direction> adapter = new ArrayAdapter<Direction>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
// Will be called via the onClick attribute
// of the buttons in main.xml
public void onClick(View view) {
@SuppressWarnings("unchecked")
ArrayAdapter<Direction> adapter = (ArrayAdapter<Direction>)
getListAdapter();
Direction direction = null;
switch (view.getId()) {
case R.id.add:
String[] ensaf = new String[] { "Scolarite", "Biblioteque",
"Service Technique","Ressources Humaines" };
int nextInt = new Random().nextInt(3);
// save the new comment to the database
direction = datasource.createDirection(ensaf[nextInt]);
adapter.add(direction);
break;
case R.id.delete:
if (getListAdapter().getCount() > 0) {
direction = (Direction) getListAdapter().getItem(0);
datasource.deleteDirection(direction);
adapter.remove(direction);
}
break;
}
adapter.notifyDataSetChanged();
}
@Override
protected void onResume() {
try {
datasource.open();
} catch (SQLException e) {
6. ENSAF Pr. A. JEGHAL Programmation mobile M : IOSEM 2020/2021
6
e.printStackTrace();
}
super.onResume();
}
@Override
protected void onPause() {
datasource.close();
super.onPause();
}
}
Tester l’application et examiner le programme.