这是我的代码。我使用“sqlite 浏览器”创建了一个 .db 文件,并将其放入工作空间的“assets”文件夹中。但是“.db”文件没有复制到应用程序路径中(当我签入 DDMS(data/data/com.example.trans/) 数据库文件夹时没有创建)。.db 文件也不是从 assets 文件夹中复制的。
这是我的代码:
public class ConnectionFactory extends SQLiteOpenHelper{
private static String DB_Path = "/data/data/com.example.translationapp/databases/";
public static String DB_Name = "Translator.db";
public SQLiteDatabase myDb;
File dbFile;
public Context con;
public ConnectionFactory(Context context) {
super(context, DB_Name, null,1);
// TODO Auto-generated constructor stub
this.con= context;
}
public void OpenDb() throws IOException
{
boolean dbCheck = checkDb();
if(dbCheck)
{
}
else
{
this.getWritableDatabase();
try
{
copyDatabase();
}
catch(IOException e)
{
throw new Error("Sorry");
}
}
}
public boolean checkDb() throws IOException
{
SQLiteDatabase checkDb =null;
try
{
String myPath = DB_Path+DB_Name;
checkDb = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
catch(SQLiteException e)
{
}
if(checkDb!= null)
{
checkDb.close();
}
return checkDb !=null ? true:false;
}
public void copyDatabase()throws IOException
{
try
{
File filetext = con.getFileStreamPath(DB_Name);
boolean exists = filetext.exists();
if(!exists)
{
String outFileName = DB_Path+ DB_Name;
myDb=con.openOrCreateDatabase(outFileName, Context.MODE_PRIVATE, null );
OutputStream myOut = new FileOutputStream(filetext.getAbsolutePath());
InputStream myin = con.getAssets().open(DB_Name);
byte[] buffer = new byte[1024];
int length;
while((length = myin.read(buffer))>0)
{
myOut.write(buffer,0,length);
}
myOut.flush();
myOut.close();
myin.close();
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
public void openDatabase() throws SQLException
{
String myPath = DB_Path+DB_Name;
myDb = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
public synchronized void close()
{
if(myDb != null)
{
myDb.close();
super.close();
}
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}