SlideShare a Scribd company logo
1 of 33
Download to read offline
A EVOLUÇÃO DA
PERSISTÊNCIA DE
DADOS (COM SQLITE)
NO ANDROID
http://bit.ly/evolucao-persistencia
RODRIGO CASTRO
Desenvolvedor Android @ Concrete
Analista de Sistemas pela UFMS/CPCX.
De Coxim/MS para o mundo!
http://castrors.github.io
rodrigo.castro@concrete.com.br
@rodrigocastro_o
SUMÁRIO
Conteúdo
• SQLiteOpenHelper
• Libs de terceiros
• Room API
SQLITE OPEN HELPER
https://developer.android.com/training/basics/data-st
orage/databases.html
SETUP
public class LoanDbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
static final String DATABASE_NAME = "openhelper.db";
private static final String TAG = "LoanDbHelper";
private LoanDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
ON CREATE E ON UPGRADE
@Override
public void onCreate(SQLiteDatabase db) {
final String SQL_CREATE_BOOK_TABLE = "CREATE TABLE " +
BookEntry.TABLE_NAME + " (" +
BookEntry._ID + " INTEGER PRIMARY KEY," +
BookEntry.COLUMN_TITLE + " TEXT NOT NULL);";
db.execSQL(SQL_CREATE_BOOK_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion != newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + BookEntry.TABLE_NAME);
onCreate(db);
}
}
INSERT
public void addBook(Book book) {
SQLiteDatabase db = getWritableDatabase();
db.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put(BookEntry._ID, book.getId());
values.put(BookEntry.COLUMN_TITLE, book.getTitle());
db.insertOrThrow(BookEntry.TABLE_NAME, null, values);
db.setTransactionSuccessful();
} catch (Exception e) {
Log.d(TAG, "Error while trying to add book to database");
} finally {
db.endTransaction();
}
}
SELECT
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM book", null);
try {
if (cursor.moveToFirst()) {
do {
int bookId = cursor.getInt(cursor.getColumnIndex(BookEntry._ID));
String title = cursor.getString(cursor.getColumnIndex(BookEntry.COLUMN_TITLE));
Book book = new Book(bookId, title);
books.add(book);
} while (cursor.moveToNext());
}
} catch (Exception e) {
Log.d(TAG, "Error while trying to get books from database");
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
BIBLIOTECAS ORM DE
TERCEIROS
https://android-arsenal.com/tag/69?sort=created
https://www.sitepoint.com/5-best-android-orms/
ORMLITE
@DatabaseTable(tableName = "user")
public class User {
@DatabaseField(id = true)
private String username;
@DatabaseField
private String password;
public User() {
// ORMLite needs a no-arg constructor
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
// Implementing getter and setter methods
}
SURGAR ORM
public class User extends SugarRecord<User> {
String username;
String password;
int age;
@Ignore
String bio; //this will be ignored by SugarORM
public User() { }
public User(String username, String password,int age){
this.username = username;
this.password = password;
this.age = age;
}
}
ACTIVE ANDROID
@Table(name = "User")
public class User extends Model {
@Column(name = "username")
public String username;
@Column(name = "password")
public String password;
public User() {
super();
}
public User(String username,String password) {
super();
this.username = username;
this.password = password;
}
}
GREEN DAO
@Entity(indexes = {
@Index(value = "username DESC", unique = true)
})
public class User {
@Id
private Long id;
@NotNull
private String username;
private String password;
//getters and setters
}
ANDROID DEV SUMMIT 2015 (44:02 - 44:53)
TÍTULO
SLIDES
GOOGLE I/O 2017 (2:26 - 2:35)
ROOM API
https://developer.android.com/topic/libraries/architec
ture/room.html
SETUP
compile 'android.arch.persistence.room:runtime:1.0.0-alpha3'
annotationProcessor 'android.arch.persistence.room:compiler:1.0.0-alpha3'
ENTITY
@Entity
public class User {
@PrimaryKey
String id;
String name;
String lastName;
int age;
}
DATABASE
@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
private static AppDatabase instance;
public abstract UserDao userModel();
public static AppDatabase getDatabase(Context context) {
if (instance == null) {
instance = Room.databaseBuilder(context,
AppDatabase.class, "database-name").build();
}
return instance;
}
public static void destroyInstance() {
instance = null;
}
}
DAO
@Dao
public interface UserDao {
@Query("select * from user")
List<User> loadAllUsers();
@Query("select * from user where id = :id")
User loadUserById(int id);
@Query("select * from user where name = :firstName and lastName = :lastName")
List<User> findByNameAndLastName(String firstName, String lastName);
}
DAO
@Dao
public interface UserDao {
@Insert(onConflict = IGNORE)
void insertOrReplaceUsers(User... users);
@Delete
void deleteUsers(User user1, User user2);
}
DAO
@Dao
public interface UserDao {
@Query("select name from user")
List<String> loadAllUserNames();
@Query("select age, name from user")
List<Pojo> loadAllUsersWithAgeAndName();
class Pojo {
int age;
String name;
}
}
ERRORS
SQLiteOpenHelper - Runtime Exception
Caused by: android.database.sqlite.SQLiteException: no such table: users
(code 1): , while compiling: SELECT * FROM users
Room API - Compile Error
Error:(31, 18) error: There is a problem with the query: [SQLITE_ERROR]
SQL error or missing database (no such table: users)
TYPE CONVERTER
public class DateConverter {
@TypeConverter
public static Date toDate(Long timestamp) {
return timestamp == null ? null : new Date(timestamp);
}
@TypeConverter
public static Long toTimestamp(Date date) {
return date == null ? null : date.getTime();
}
}
@TypeConverters(DateConverter.class)
EMBEDDED
@Entity
public class User {
@PrimaryKey
String id;
String name;
String lastName;
int age;
Location location;
}
Error:(29, 21) error: Cannot figure out how to save this field into database.
You can consider adding a type converter for it.
EMBEDDED
@Entity
public class User {
@PrimaryKey
String id;
String name;
String lastName;
int age;
@Embedded
Location location;
}
SMART JOIN
@Query("SELECT Loan.id, Book.title, User.name, Loan.startTime, Loan.endTime From Loan " +
"INNER JOIN Book ON Loan.book_id = Book.id " +
"INNER JOIN User ON Loan.user_id = User.id ")
List<LoanWithUserAndBook> findAllWithUserAndBook();
@Query("SELECT startTime, name From Loan, User " +
"WHERE Loan.user_id = User.id ")
List<StartTimeWithUsername> findLoanStartTimeWithUsername();
class StartTimeWithUsername {
Date startTime;
String name;
}
MAIS ALGUMAS FEATURES
INDEX
MIGRATIONS
TESTABILITY
LINKS INTERESSANTES
https://github.com/castrors/PersistenceTalk
https://developer.android.com/topic/libraries/architecture/index.html
https://codelabs.developers.google.com/codelabs/android-persistence/index.html
https://codelabs.developers.google.com/codelabs/android-lifecycles/index.html
https://www.youtube.com/watch?v=MfHsPGQ6bgE
https://www.youtube.com/watch?v=FrteWKKVyzI
OBRIGADO!
Centro
Av. Presidente Wilson,
231 - 29º andar
(21) 2240-2030
Cidade Monções
Av. Nações Unidas,
11.541 - 3º andar
(11) 4119-0449
Savassi
Av. Getúlio Vargas, 671
Sala 800 - 8º andar
(31) 3360-8900
www.concrete.com.br

More Related Content

What's hot

JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
Kiyotaka Oku
 
Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! 
aleks-f
 
Sistema de ventas
Sistema de ventasSistema de ventas
Sistema de ventas
DAYANA RETO
 

What's hot (19)

JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
 
Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! Look Ma, “update DB to HTML5 using C++”, no hands! 
Look Ma, “update DB to HTML5 using C++”, no hands! 
 
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
«Objective-C Runtime в примерах» — Алексей Сторожев, e-Legion
 
Hidden Treasures of the Python Standard Library
Hidden Treasures of the Python Standard LibraryHidden Treasures of the Python Standard Library
Hidden Treasures of the Python Standard Library
 
Android Developer Toolbox 2017
Android Developer Toolbox 2017Android Developer Toolbox 2017
Android Developer Toolbox 2017
 
SISTEMA DE FACTURACION (Ejemplo desarrollado)
SISTEMA DE FACTURACION (Ejemplo desarrollado)SISTEMA DE FACTURACION (Ejemplo desarrollado)
SISTEMA DE FACTURACION (Ejemplo desarrollado)
 
Tools and Projects Dec 2018 Edition
Tools and Projects Dec 2018 EditionTools and Projects Dec 2018 Edition
Tools and Projects Dec 2018 Edition
 
16 18
16 1816 18
16 18
 
Design Patterns Reconsidered
Design Patterns ReconsideredDesign Patterns Reconsidered
Design Patterns Reconsidered
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
Sistema de ventas
Sistema de ventasSistema de ventas
Sistema de ventas
 
Sequelize
SequelizeSequelize
Sequelize
 
How to Bring Common UI Patterns to ADF
How to Bring Common UI Patterns to ADF How to Bring Common UI Patterns to ADF
How to Bring Common UI Patterns to ADF
 
Selectors and normalizing state shape
Selectors and normalizing state shapeSelectors and normalizing state shape
Selectors and normalizing state shape
 
Visual Studio.Net - Sql Server
Visual Studio.Net - Sql ServerVisual Studio.Net - Sql Server
Visual Studio.Net - Sql Server
 
Rails Model Basics
Rails Model BasicsRails Model Basics
Rails Model Basics
 
mobl
moblmobl
mobl
 
Paradigmas de programação funcional + objetos no liquidificador com scala
Paradigmas de programação funcional + objetos no liquidificador com scalaParadigmas de programação funcional + objetos no liquidificador com scala
Paradigmas de programação funcional + objetos no liquidificador com scala
 

Similar to A evolução da persistência de dados (com sqlite) no android

Jersey framework
Jersey frameworkJersey framework
Jersey framework
knight1128
 

Similar to A evolução da persistência de dados (com sqlite) no android (20)

Android Architecture Components - Guy Bar on, Vonage
Android Architecture Components - Guy Bar on, VonageAndroid Architecture Components - Guy Bar on, Vonage
Android Architecture Components - Guy Bar on, Vonage
 
Architecture components - IT Talk
Architecture components - IT TalkArchitecture components - IT Talk
Architecture components - IT Talk
 
Architecture Components
Architecture Components Architecture Components
Architecture Components
 
Codemotion appengine
Codemotion appengineCodemotion appengine
Codemotion appengine
 
Dev Day Andreas Roth.pdf
Dev Day Andreas Roth.pdfDev Day Andreas Roth.pdf
Dev Day Andreas Roth.pdf
 
Architecture Components
Architecture ComponentsArchitecture Components
Architecture Components
 
Save data in to sqlite
Save data in to sqliteSave data in to sqlite
Save data in to sqlite
 
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
 
Using database in android
Using database in androidUsing database in android
Using database in android
 
Struts 2 + Spring
Struts 2 + SpringStruts 2 + Spring
Struts 2 + Spring
 
Lombokの紹介
Lombokの紹介Lombokの紹介
Lombokの紹介
 
Android Architecture - Khoa Tran
Android Architecture -  Khoa TranAndroid Architecture -  Khoa Tran
Android Architecture - Khoa Tran
 
ANDROID USING SQLITE DATABASE ADMINISTRATORS ~HMFTJ
ANDROID USING SQLITE DATABASE ADMINISTRATORS ~HMFTJANDROID USING SQLITE DATABASE ADMINISTRATORS ~HMFTJ
ANDROID USING SQLITE DATABASE ADMINISTRATORS ~HMFTJ
 
Jersey framework
Jersey frameworkJersey framework
Jersey framework
 
Android architecture component - FbCircleDev Yogyakarta Indonesia
Android architecture component - FbCircleDev Yogyakarta IndonesiaAndroid architecture component - FbCircleDev Yogyakarta Indonesia
Android architecture component - FbCircleDev Yogyakarta Indonesia
 
Introduction à Dart
Introduction à DartIntroduction à Dart
Introduction à Dart
 
Android best practices
Android best practicesAndroid best practices
Android best practices
 
BigQuery JavaScript User-Defined Functions by THOMAS PARK and FELIPE HOFFA at...
BigQuery JavaScript User-Defined Functions by THOMAS PARK and FELIPE HOFFA at...BigQuery JavaScript User-Defined Functions by THOMAS PARK and FELIPE HOFFA at...
BigQuery JavaScript User-Defined Functions by THOMAS PARK and FELIPE HOFFA at...
 
Teste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrityTeste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrity
 
Spring boot
Spring boot Spring boot
Spring boot
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 

A evolução da persistência de dados (com sqlite) no android