【发布时间】:2015-10-26 18:22:54
【问题描述】:
我想用嵌入式数据库发布我的 android 应用程序。在网上搜索我发现人们将它放在应用程序的资产中,然后在安装时/首次运行时将其复制到其他目录。
在我的情况下,我需要一个只读数据库,所以我不想制作它的多个副本。是否可以直接从资产中使用它?有没有办法节省这个空间?
【问题讨论】:
-
为什么有人会否决这个问题?这没有意义。
我想用嵌入式数据库发布我的 android 应用程序。在网上搜索我发现人们将它放在应用程序的资产中,然后在安装时/首次运行时将其复制到其他目录。
在我的情况下,我需要一个只读数据库,所以我不想制作它的多个副本。是否可以直接从资产中使用它?有没有办法节省这个空间?
【问题讨论】:
在我的情况下,我需要一个只读数据库,所以我不想制作它的多个副本。是否可以直接从资产中使用它?有没有办法节省这个空间?
没有。资产不是您设备中的常规文件,sqlite 库无法直接读取它们。
要么使用例如复制文件。 sqlite-asset-helper 或者不使用 sqlite 数据库,而是可以使用 AssetManager 提供的 InputStreams 的东西。
【讨论】:
AFAIK,这是不可能的。
【讨论】:
我认为这是不可能的,在这里查看类似的问题:Reading sqlite file from asset folder
要使用数据库你需要把它复制到assets文件夹到文件夹到app里面的某个目录。
检查此代码。
public class DataBaseHelper extends SQLiteOpenHelper {
private Context mycontext;
private static String DB_NAME = "(datbasename).sqlite";
public SQLiteDatabase myDataBase;
public DataBaseHelper(Context context) throws IOException {
super(context,DB_NAME,null,1);
this.mycontext=context;
boolean dbexist = checkdatabase();
if (dbexist) {
//System.out.println("Database exists");
opendatabase();
} else {
System.out.println("Database doesn't exist");
createdatabase();
}
}
public void createdatabase() throws IOException {
boolean dbexist = checkdatabase();
if(dbexist) {
System.out.println(" Database exists.");
} else {
this.getReadableDatabase();
try {
copydatabase();
} catch(IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkdatabase() {
boolean checkdb = false;
try {
String myPath = DB_PATH + DB_NAME;
File dbfile = new File(myPath);
checkdb = dbfile.exists();
} catch(SQLiteException e) {
System.out.println("Database doesn't exist");
}
return checkdb;
}
private void copydatabase() throws IOException {
//Open your local db as the input stream
InputStream myinput = mycontext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outfilename = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myoutput = new FileOutputStream("/data/data/(packagename)/databases /(datbasename).sqlite");
// transfer byte to inputfile to outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myinput.read(buffer))>0) {
myoutput.write(buffer,0,length);
}
//Close the streams
myoutput.flush();
myoutput.close();
myinput.close();
}
public void opendatabase() throws SQLException {
//Open the database
String mypath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(mypath, null, SQLiteDatabase.OPEN_READWRITE);
}
public synchronized void close() {
if(myDataBase != null) {
myDataBase.close();
}
super.close();
}
}
【讨论】: