首先将数据库从资产文件夹复制到应用程序数据库文件夹。
这是复制数据库的代码
public class DataBaseWrapper extends SQLiteOpenHelper
{
private static String TAG = DataBaseWrapper.class.getName();
private String DB_PATH; //= "/data/data/com.example.yourproject/databases/";
private static String DB_NAME = "Database.sqlite";
private SQLiteDatabase myDataBase = null;
private final Context myContext;
public DataBaseWrapper(Context context)
{
super(context, DB_NAME, null, 1);
this.myContext = context;
DB_PATH="/data/data/" + context.getPackageName() + "/" + "databases/";
Log.v("log_tag", "DBPath: " + DB_PATH);
// File f=getDatabasePath(DB_NAME);
}
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
if(dbExist){
Log.v("log_tag", "database does exist");
}else{
Log.v("log_tag", "database does not exist");
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private void copyDataBase() throws IOException{
InputStream myInput = myContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
private boolean checkDataBase(){
File dbFile = new File(DB_PATH + DB_NAME);
//Log.v("dbFile", dbFile + " "+ dbFile.exists());
return dbFile.exists();
}
public boolean openDataBase() throws SQLException
{
String mPath = DB_PATH + DB_NAME;
//Log.v("mPath", mPath);
myDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.CREATE_IF_NECESSARY);
//mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
return myDataBase != null;
}
@Override
public synchronized void close()
{
if(myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db)
{
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.v(TAG, "Upgrading database, this will drop database and recreate.");
}
}
另请检查此链接..它可能对您有用在 Robolectric 中测试 SQLite 数据库 https://stackoverflow.com/questions/7320820/testing-sqlite-database-in-robolectric?rq=1
尝试这些事情:
1.从终端删除您的数据库
adb shell
cd /data/data/com.example.apploicationname/databases
rm *
并在模拟器上再次重新安装您的应用程序。
尝试增加模拟器的 RAM.. 尽管数据库中有所有数据,但我还是遇到了同样的错误,但是当我将模拟器的 RAM 从 1024 增加到 2000 时.. 它起作用了。
将数据库从 DDMS 复制到系统文件系统并通过 sqlite 浏览器打开它并检查表是否存在。
sqlite 浏览器的链接http://sourceforge.net/projects/sqlitebrowser/files/sqlitebrowser/ http://sourceforge.net/projects/sqlitebrowser/files/sqlitebrowser/