3. 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
6. 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);
}
7. 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);
}
}
8. 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();
}
}
9. 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();
}
}
11. 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
}
12. 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;
}
}
13. 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;
}
}
14. 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
}
21. 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;
}
}
22. 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);
}
23. DAO
@Dao
public interface UserDao {
@Insert(onConflict = IGNORE)
void insertOrReplaceUsers(User... users);
@Delete
void deleteUsers(User user1, User user2);
}
24. 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;
}
}
25. 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)
26. 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)
27. 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.
33. 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