Académique Documents
Professionnel Documents
Culture Documents
1
Prof. Dr. Yassine Rhazali
1 SQLite
SQLite est une base de données relationnelle, source ouverte, elle est construite sur le système
d'exploitation Android, afin que vous puissiez l'utiliser à tout moment et sans autre configuration.
En général, avec des bases de données telles que Oracle, MySQL, ... vous avez besoin d'une
bibliothèque Driver et créez une connexion JDBC, mais avec SQLite, il n'est pas nécessaire.
Aperçu de l'exemple:
2
Prof. Dr. Yassine Rhazali
Voici le menu
3
Prof. Dr. Yassine Rhazali
3 Les étapes pour travailler avec la base de
données SQLite
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().
• 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.
4
Prof. Dr. Yassine Rhazali
• 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
MyDatabaseHelper.java
public class MyDatabaseHelper extends SQLiteOpenHelper {
// ....
@Override
public void onCreate(SQLiteDatabase db) {
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop table
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTE);
// Recreate
onCreate(db);
}
// ...
}
5
Prof. Dr. Yassine Rhazali
• Name: SQLiteDemo
• Package name: org.o7planning.sqlitedemo
6
Prof. Dr. Yassine Rhazali
Créez un nouveau Activity vide.
• File/New/Activity/Empty Activity
Saisissez:
7
Prof. Dr. Yassine Rhazali
4.1 activity_main.xml
8
Prof. Dr. Yassine Rhazali
activity_main.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"
tools:context=".MainActivity">
<ListView
android:id="@+id/listView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="16dp"
9
Prof. Dr. Yassine Rhazali
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="16dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
4.2 activity_add_edit_note.xml
Puis
10
Prof. Dr. Yassine Rhazali
Ensuite
Ensuite
11
Prof. Dr. Yassine Rhazali
Ensuite presque la même on doit affecter les mêmes valeurs pour tous les composants
d’interface.
12
Prof. Dr. Yassine Rhazali
activity_add_edit_note.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"
tools:context=".AddEditNoteActivity">
<EditText
android:id="@+id/editText_note_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
13
Prof. Dr. Yassine Rhazali
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:ems="10"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/editText_note_content"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="16dp"
android:ems="10"
android:inputType="textMultiLine"
app:layout_constraintBottom_toTopOf="@+id/linearLayout3"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText_note_title" />
<LinearLayout
android:id="@+id/linearLayout3"
14
Prof. Dr. Yassine Rhazali
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="16dp"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<Button
android:id="@+id/button_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Save" />
<Button
android:id="@+id/button_cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Cancel" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
5 Java Code
15
Prof. Dr. Yassine Rhazali
Note.java
package org.o7planning.sqlitedemo.bean;
import java.io.Serializable;
public Note() {
16
Prof. Dr. Yassine Rhazali
return noteTitle;
}
@Override
public String toString() {
return this.noteTitle;
}
MyDatabaseHelper.java
package org.o7planning.sqlitedemo;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import org.o7planning.sqlitedemo.bean.Note;
import java.util.ArrayList;
import java.util.List;
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "Note_Manager";
17
Prof. Dr. Yassine Rhazali
private static final String COLUMN_NOTE_ID ="Note_Id";
private static final String COLUMN_NOTE_TITLE ="Note_Title";
private static final String COLUMN_NOTE_CONTENT = "Note_Content";
// Create table
@Override
public void onCreate(SQLiteDatabase db) {
Log.i(TAG, "MyDatabaseHelper.onCreate ... ");
// Script.
String script = "CREATE TABLE " + TABLE_NOTE + "("
+ COLUMN_NOTE_ID + " INTEGER PRIMARY KEY," +
COLUMN_NOTE_TITLE + " TEXT,"
+ COLUMN_NOTE_CONTENT + " TEXT" + ")";
// Execute Script.
db.execSQL(script);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
SQLiteDatabase db = this.getWritableDatabase();
18
Prof. Dr. Yassine Rhazali
values.put(COLUMN_NOTE_CONTENT, note.getNoteContent());
// Inserting Row
db.insert(TABLE_NOTE, null, values);
SQLiteDatabase db = this.getReadableDatabase();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
19
Prof. Dr. Yassine Rhazali
public int getNotesCount() {
Log.i(TAG, "MyDatabaseHelper.getNotesCount ... " );
cursor.close();
// return count
return count;
}
SQLiteDatabase db = this.getWritableDatabase();
// updating row
return db.update(TABLE_NOTE, values, COLUMN_NOTE_ID + " = ?",
new String[]{String.valueOf(note.getNoteId())});
}
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NOTE, COLUMN_NOTE_ID + " = ?",
new String[] { String.valueOf(note.getNoteId()) });
db.close();
}
MainActivity.java
package org.o7planning.sqlitedemo;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.ContextMenu;
20
Prof. Dr. Yassine Rhazali
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import org.o7planning.sqlitedemo.bean.Note;
import java.util.ArrayList;
import java.util.List;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
21
Prof. Dr. Yassine Rhazali
@Override
public void onCreateContextMenu(ContextMenu menu, View view,
ContextMenu.ContextMenuInfo
menuInfo) {
@Override
public boolean onContextItemSelected(MenuItem item){
AdapterView.AdapterContextMenuInfo
info = (AdapterView.AdapterContextMenuInfo)
item.getMenuInfo();
if(item.getItemId() == MENU_ITEM_VIEW){
Toast.makeText(getApplicationContext(),selectedNote.getNoteCont
ent(),Toast.LENGTH_LONG).show();
}
else if(item.getItemId() == MENU_ITEM_CREATE){
Intent intent = new Intent(this, AddEditNoteActivity.class);
22
Prof. Dr. Yassine Rhazali
}
else {
return false;
}
return true;
}
// Delete a record
private void deleteNote(Note note) {
MyDatabaseHelper db = new MyDatabaseHelper(this);
db.deleteNote(note);
this.noteList.remove(note);
// Refresh ListView.
this.listViewAdapter.notifyDataSetChanged();
}
AddEditNoteActivity.java
package org.o7planning.sqlitedemo;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.app.Activity;
import org.o7planning.sqlitedemo.bean.Note;
23
Prof. Dr. Yassine Rhazali
public class AddEditNoteActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_edit_note);
this.textTitle =
(EditText)this.findViewById(R.id.editText_note_title);
this.textContent =
(EditText)this.findViewById(R.id.editText_note_content);
this.buttonSave = (Button)findViewById(R.id.button_save);
this.buttonCancel = (Button)findViewById(R.id.button_cancel);
this.buttonSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
buttonSaveClicked();
}
});
this.buttonCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
buttonCancelClicked();
}
});
24
Prof. Dr. Yassine Rhazali
if(title.equals("") || content.equals("")) {
Toast.makeText(getApplicationContext(),
"Please enter title & content",
Toast.LENGTH_LONG).show();
return;
}
if(mode == MODE_CREATE ) {
this.note= new Note(title,content);
db.addNote(note);
} else {
this.note.setNoteTitle(title);
this.note.setNoteContent(content);
db.updateNote(note);
}
this.needRefresh = true;
// Back to MainActivity.
this.onBackPressed();
}
// Create Intent
Intent data = new Intent();
// Set Result
this.setResult(Activity.RESULT_OK, data);
super.finish();
}
25
Prof. Dr. Yassine Rhazali