-
Notifications
You must be signed in to change notification settings - Fork 5
Getting started
Andrew Horishnii edited this page Aug 9, 2016
·
9 revisions
Gradle dependency:
repositories {
jcenter()
}
dependencies {
compile 'com.github.andreyrage:leftdb:1.5'
}public class DbHelper extends LeftDBUtils {
private static volatile DbHelper sInstance;
private DbHelper() {
...
}
public static DbHelper getInstance(Context context) {
DbHelper localInstance = sInstance;
if (localInstance == null) {
synchronized (DbHelper.class) {
localInstance = sInstance;
if (localInstance == null) {
sInstance = localInstance = new DbHelper();
localInstance.setDBContext(context, "sample.sqlite", 1);
}
}
}
return localInstance;
}
@Override
public void onCreate(SQLiteDatabase db) {
super.onCreate(db);
createTable(db, SimpleEntity.class);
}
...
}Also need override serializeObject(Object object) and deserializeObject(String string, Class tClass, final Type genericType). In these methods need realize serialization object to string and deserialization from string to object if you want use annotation @ColumnDAO.
For example you can do it with gson:
private final Gson mGson = new Gson();
...
@Override
protected String serializeObject(Object object) {
return mGson.toJson(object);
}
@Override
protected <T> T deserializeObject(String string, Class<T> tClass, final Type genericType) {
return mGson.fromJson(string, genericType);
}or with jackson:
private final ObjectMapper mMapper = new ObjectMapper()
.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
...
@Override
protected String serializeObject(Object object) {
try {
return mMapper.writeValueAsString(object);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected <T> T deserializeObject(String string, Class<T> tClass, final Type genericType) {
try {
return mMapper.readValue(string, new TypeReference<Object>() {
@Override public Type getType() {
return genericType;
}
});
} catch (IOException e) {
e.printStackTrace();
}
return null;
}public class SimpleEntity {
@ColumnAutoInc private Long id;
@ColumnName("name") private String entityName;
@ColumnDAO private Properties properties;
public SimpleEntity() {
}
...
}More for creating entities read here.
For example:
DbHelper dbHelper = DbHelper.getInstance(this);
SimpleEntity simpleEntity = new SimpleEntity();
dbHelper.add(simpleEntity); //save in the database
List<SimpleEntity> entities
= dbHelper.getAll(SimpleEntity.class); //get all SimpleEntity objects from database
dbHelper.delete(simpleEntity); //delete object from databaseTo execute in not UI thread you can use AsyncCall:
AsyncCall.make(new AsyncCall.Call<List<SimpleEntity>>() {
@Override
public List<SimpleEntity> call() {
return dbHelper.getAll(SimpleEntity.class)
}
}, new AsyncCall.Do<List<SimpleEntity>>() {
@Override
public void doNext(List<SimpleEntity> simpleEntities) {
// returned result to UI thread
}
}).call();