0% found this document useful (0 votes)
51 views

Advanced Mobile Development: Nabeul 2019

This document discusses data persistence in Android applications using SQLite. It begins by introducing different data storage options like internal storage, shared preferences, and SQLite database. It then focuses on using SQLite as a local database to store application data. The key aspects covered include using SQLiteOpenHelper to manage the database, implementing CRUD operations through a DAO class, and tying it together in an activity. Sample code is provided to demonstrate creating a database, model class, DAO class with CRUD methods, and using it in an activity to add, delete and display data from the SQLite database.

Uploaded by

Omar Ben Omrane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

Advanced Mobile Development: Nabeul 2019

This document discusses data persistence in Android applications using SQLite. It begins by introducing different data storage options like internal storage, shared preferences, and SQLite database. It then focuses on using SQLite as a local database to store application data. The key aspects covered include using SQLiteOpenHelper to manage the database, implementing CRUD operations through a DAO class, and tying it together in an activity. Sample code is provided to demonstrate creating a database, model class, DAO class with CRUD methods, and using it in an activity to add, delete and display data from the SQLite database.

Uploaded by

Omar Ben Omrane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Advanced Mobile development

SEM 31
Nabeul 2019
Chapter 4
Data persistence
-SQLite-
Plan
01 Internal & external data storage

02 Shared preference

03 Local data base storage SQLite

03 CRUD Operations
Introduction
How to save your app data?

The solution to choose depends on:

 How much space your data requires;

 What kind of data you need to store;

 Whether the data should be private to your app or acces


sible to other apps and the user.
How to save your app data?

The solution to choose depends on:


Internal Storage
 Storage private to your app;

The system provides a private directory on the file system


for each app where you can organize any files your app needs
;

When the user uninstalls your app, the files saved on the
internal storage are removed;
External Storage
 Storage space that users can mount to a computer as an
external storage device, and it might even be physically
removable (such as an SD card).

 Used for data that should be accessible to other apps and


saved even if the user uninstalls your app (captured photos or
downloaded files).

The system provides standard public directories for these


kinds of files.
Shared preference
 Used if you don't need to store a lot of data and it doesn't r
equire structure.

 This APIs allow you to read and write persistent key-value


pairs of data.

The key-value pairs are written to XML files that persist


across user sessions, even if your app is killed.

Example: Setting as ringtone, high score…


Data Base

Local Remote
Data Base Data Base
SQLite
- Definition-
SQlite: Presentation

 Local Data Base;

 Data are private ;

Any database you create is accessible


only by your app;
https://www.sqlite.org
 Data storage file: /data/data/ « name space »/databa
ses
SQLite: how to use it?
How to manage your project?

We need to isolate the application/business layer from the persistence


layer.

 Data model Class;


 DAO Class (Data Access Object);
 SQLiteOpenHelper Class;
 Main Activity;
SQLite: how to use it?

A helper class to manage database


creation and version management.
 Data model Class;

 SQLiteOpenHelper Class;

DAO Class (Data Access Object);

 Main Activity;
SQLite: how to use it?
Representation of our data (tables attributes)

 Data model Class;

 DAO Class (Data Access Object);

 SQLiteOpenHelper Class;

 Main Activity;
SQLiteOpenHelper Class
public class DataBaseHandler extends SQLiteOpenHelper {
public DataBaseHandler(Context context, String dbname,
SQLiteDatabase.CursorFactory factory, int version) {
super(context, dbname, factory, version);
//Constructor & create DB
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
//Create tables
}
@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
//Upgrade DataBase
}}
How to create a DB?
public static final int DATABASE_VERSION = 1; // DB Version
public static final String DATABASE_NAME = "product.db";// DB na
me

public DataBaseHandler(Context context, String name, SQLiteDatab


ase.CursorFactory factory, int version) {
//super(context, name, factory, version);
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

//…

}
How to execute a statment?
public void execSQL (String sql)

 Added in API level 1

Execute a single SQL statement that is NOT a SELECT or any other SQL stat
ement that returns data.

Example: create a table, delete a table…


How to execute a statment?
CREATE a table
public static final String CREATE_TABLE= " create table product (
id INTEGER PRIMARY KEY, name TEXT, quantity INTEGER); ";

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(CREATE_TABLE);
}
How to execute a statment?
DROP a table

public static final String DROP_Table = “DROP TABLE IF EXISTS pro


duct ;";

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i
1) {
sqLiteDatabase.execSQL(ProductDAO.DROP_TABLE);
onCreate(sqLiteDatabase);}
SQLite: how to use it?

 Data model Class; CRUD Operations

 SQLiteOpenHelper Class;

DAO Class (Data Access Object);

 Main Activity;
SQLite
- CRUD Operation-
Insert Data
1) access the database in write mode
SQLiteDatabase db = SQLiteOpenHelper.getWritableDatabase();

2) Prepare the data to insert => ContentValue


ContentValues v = new ContentValues();
v.put("id" ,12);
v.put("name", "produit1");
v.put("quantity", 1);

3) Insert data into the DB


db.insert("product", null, v);//null column hack
db.close();
Delete Data

1) access the database in write mode


SQLiteDatabase db = SQLiteOpenHelper.getWritableDatabase();

2) Delete Data

Integer var=2;

db.delete("product","id='"+var+"'",null);// Where clause and where args


Update Data
1) access the database in write mode
SQLiteDatabase db = SQLiteOpenHelper.getWritableDatabase();

2) Prepare the data to set => ContentValue


ContentValues v = new ContentValues();
v.put("id" ,12);
v.put("name", "produit1");
v.put("quantity", 100);

3) Update data into the DB

db.update(“product",v, “id=12", null);


Select Data

1) access the database in read mode


SQLiteDatabase db = dbHandler.getReadableDatabase();

2) Get Data

Cursor c=db.rawQuery("SELECT * FROM product",null);


//We can test the c.getCount()==0
while (c.moveToNext()) {
//c.getInt(0)
//c.getString(1)
//c.getInt(2));
}
Example
Project Structure

product(id, name, quantity)

Autoincrement
Data Model: Product.java
public class Product {
//--------Attribute
Integer Id;
String Name;
Integer Quantity;
// -------------Constructor
public Product(){ }
public Product(Integer id, String name, Integer quantity) {
super();
this.Id = id;
this.Name = name;
this.Quantity = quantity;
}

//--------------getters & setters



}
SQLiteOpenHelper : DataBaseHandler.java
public class DataBaseHandler extends SQLiteOpenHelper {

public static final int DATABASE_VERSION = 1; // DB Version


public static final String DATABASE_NAME = "product.db";// DB name

public DataBaseHandler(Context context, String name, SQLiteDatabase.CursorFa


ctory factory, int version) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(ProductDAO.CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL(ProductDAO.DROP_TABLE);
onCreate(sqLiteDatabase);}
Controller: ProductDAO.java

public class ProductDAO {


//Attributes
public static final String CREATE_TABLE = "create table product ( id INTEG
ER PRIMARY KEY, name TEXT, quantity INTEGER);" ;

public static final String DROP_TABLE="DROP TABLE IF EXISTS product ";

public DataBaseHandler dbHandler;

//Constructor
public ProductDAO(Context context) {
dbHandler = new DataBaseHandler(context,"", null,1);
}
Controller: ProductDAO.java
public class ProductDAO {
//Attributes and constructor

//Insert data
public void insertdata (Product p) {
SQLiteDatabase db = dbHandler.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("id" , p.getId());
values.put("name", p.getNanme());
values.put("quantity", p.getQt());
// Insertion Ligne (Row)
db.insert("product", null, values);
db.close(); // fermer la connection BD
}
}
Controller: ProductDAO.java
public class ProductDAO {
//Attributes and constructor

//insert data

public void deletedata(Integer first)


{
SQLiteDatabase db = dbHandler.getWritableDatabase();
db.delete("product","id='"+first+"'",null);

}
}
Controller: ProductDAO.java
public class ProductDAO {
//Attributes and constructor
//insert data
//Delete data

public Cursor showdata()


{
SQLiteDatabase db = dbHandler.getReadableDatabase();
String req="SELECT * FROM product";
Cursor c=db.rawQuery(req,null);
return c;
}
Main Activity
public class MainActivity extends AppCompatActivity {
EditText id, name, qt;
TextView texte;
ProductDAO DAO;
DataBaseHandler DatabaseHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DAO=new ProductDAO(this);

}
Main Activity
Main Activity: add data Product p=new Product(3, “p2”, 12);
DAO.insertdata(p);

Main Activity: delete data DAO.deletedata(3);

Main Activity: show data Cursor c=DAO.showdata();


if( c.getCount()==0 ){
//empty
}
else{
while (c.moveToNext()) {
//get data c.getInt(0) …
}}
In the end,
it’s not the years in you
r life that count.
It’s the life in your
years.
- Abraham Lincoln -

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy