I'm perfectly able to use Sugar ORM using provided examples.
In my usecase I download a SQLite DB from the server (ETL load for it is in millions of records so has to be done server side). The download saves to a custom path on internal storage.
In my case I do not need dynamic DB creation based on POCOs.
Is it possible to use Sugar ORM with pre-existing SQLite DB, pointing to a custom path, provided if all POCO classes fields match the table structure?
First of all, I am not comfortable with the idea that Sugar extends the app class. What if I have other tasks need to be carried out before app start?! So let's extend SugarApp with our own AppClass then register the appClass name in manifest. Also, this is the right place to init db the first time I believe.
public class MyAppStartClass extends SugarApp {
@Override
public final void onCreate() {
init();
super.onCreate();
}
private void init() {
initDB();
}
private void initDB() {
try {
if (!doesDatabaseExist(this, consts.dbPath)) {
Context context = getApplicationContext();
SQLiteDatabase db = context.openOrCreateDatabase(consts.dbName, context.MODE_PRIVATE, null);
db.close();
InputStream dbInput = getApplicationContext().getAssets().open(consts.dbName);
String outFileName = consts.dbPath;
OutputStream dbOutput = new FileOutputStream(outFileName);
try {
byte[] buffer = new byte[1024];
int length;
while ((length = dbInput.read(buffer)) > 0) {
dbOutput.write(buffer, 0, length);
}
} finally {
dbOutput.flush();
dbOutput.close();
dbInput.close();
}
}
} catch (Exception e) {
e.toString();
}
}
private boolean doesDatabaseExist(ContextWrapper context, String dbName) {
File dbFile = context.getDatabasePath(dbName);
return dbFile.exists();
}
}
Manifest: android:name="com.myPackageName.MyAppStartClass"
Make sure you create an empty db first, if you don't you'll get an error from FileOutputStream() and dbPath = /data/data/com.myPackageName/databases/myDb.db
SQLiteDatabase db = context.openOrCreateDatabase(consts.dbName, context.MODE_PRIVATE, null);
db.close();
Make sure your existing db schema has a primary key column ID. Oh yeah! Sugar only sees ID as primary key to retrieve data.
If you want to use existing tables, do NOT specify T when you extend SugarRecord AND you have to add Sugar as a module and your project depends on it!
public class Book extends SugarRecord {
String title;
String edition;
public Book(){
}
public Book(String title, String edition){
this.title = title;
this.edition = edition;
}
}
6.If you want to use existing tables. Be aware that Sugar looks for UPPERCASE column names so if your existing table column names are lowercase you will never get any existing data out of it!
7.That leads me to a reluctant conclusion: Sugar is great if your start db from scratch and use it to generate db and tables for you. But not so when you have already had an existing db with data in it.