我想用嵌入式数据库发送我的Android应用程序。在网上搜索我发现人们在应用程序的资产中发送它,然后在安装时/首次运行时将其复制到其他目录。
在我的情况下,我需要一个只读数据库,所以我不想制作它的多个副本。是否可以直接从资产中使用它?有没有办法保存这个空间?
答案 0 :(得分:2)
在我的情况下,我需要一个只读数据库,所以我不想制作它的多个副本。是否可以直接从资产中使用它?有没有办法保存这个空间?
没有。资产不是设备中的常规文件,sqlite库无法直接读取它们。
使用例如复制文件sqlite-asset-helper或者不使用sqlite数据库,而是可以使用InputStream
提供的AssetManager
。
答案 1 :(得分:1)
AFAIK,这是不可能的。
答案 2 :(得分:0)
我认为这是不可能的,请在此处查看类似的问题:Reading sqlite file from asset folder
要使用数据库,您需要将其复制到资源文件夹中,然后将其复制到应用程序内的目录。
检查此代码。
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();
}
}