具有现有数据库和自定义文件路径的Android Sugar ORM
|
我完全能够使用提供的示例使用Sugar ORM. 在我的用例中,我从服务器下载了一个SQLite DB(ETL加载它的数百万条记录,因此必须在服务器端完成).下载保存到内部存储上的自定义路径. 在我的情况下,我不需要基于POCO创建动态数据库. 如果所有POCO类字段都与表结构匹配,是否可以将Sugar ORM与预先存在的SQLite DB一起使用,指向自定义路径? 解决方法>首先,我对Sugar的想法感到不舒服app类.如果我还有其他任务需要执行怎么办? 在app开始之前?!所以让我们用自己的方式扩展SugarApp 然后,AppClass在清单中注册appClass名称.此外,这是我第一次相信init db的正确位置. 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,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” SQLiteDatabase db = context.openOrCreateDatabase(consts.dbName,null); db.close(); public class Book extends SugarRecord {
String title;
String edition;
public Book(){
}
public Book(String title,String edition){
this.title = title;
this.edition = edition;
}
}
6.如果要使用现有表.请注意,Sugar会查找大写列名称,因此如果您现有的表列名称为小写,则永远不会从中获取任何现有数据! 这让我得出了一个不情愿的结论:如果你从头开始db并使用它来为你生成db和table,那么Sugar就很棒.但是当你已经有一个包含数据的现有数据库时,情况并非如此. (编辑:92站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |

