我有一个应用程序必须从 assets 文件夹上的 .db 文件打开一个 sqlitedatabase。每次应用启动时都必须打开该数据库。
我正在查看一些教程以处理 android 中的 sqlite 数据库以及从文件中加载 sqlite 数据库。我在这段代码中合并了所有这些教程,但它不起作用。
我的数据库包含一个名为items
wich 的 TABLE 里面有一些数据,但是当我从中调用一个 SELECT * 语句时,items
我得到一个异常,告诉我 items 表不存在:
String databaseName="frases";
SQLiteManager sqlManager = new SQLiteManager(this);
sqlManager.open(databaseName);
List<String> nombres = new ArrayList<String>();
Cursor cursor=sqlManager.rawQuery("SELECT * FROM 'items'");
while (cursor.moveToNext()) {
nombres.add(cursor.getString(1));
}
for (int i=0; i<nombres.size();i++){
Log.d("DATABASE", "Nombre: "+nombres.get(i));
}
sqlManager.close(); //Cerramos la base de datos
这是我的 SQLiteManager 类:
public class SQLiteManager {
private DemoSQLiteHelper dbHelper;
private SQLiteDatabase db;
private static Context ctx;
public SQLiteManager(Context ctx) {
this.ctx = ctx;
}
public void open(String databaseName) throws SQLException {
dbHelper = new DemoSQLiteHelper(ctx, databaseName, null, 1);
generateSQLiteDB(databaseName);
db = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public void execSQL(String sql){
db.execSQL(sql);
}
public Cursor rawQuery(String sql){
Cursor cursor=db.rawQuery(sql, null);
return cursor;
}
public void clearDB() {
dbHelper.clearDb(db);
}
public class DemoSQLiteHelper extends SQLiteOpenHelper {
public DemoSQLiteHelper(Context contexto, String nombre, CursorFactory factory, int version) {
super(contexto, nombre, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int versionAnterior, int versionNueva) {
}
public void clearDb(SQLiteDatabase db){
onCreate(db);
}
}
private void generateSQLiteDB(String databaseName) { //
SQLiteDatabase db = dbHelper.getReadableDatabase(); // by calling this line an empty database will be created into the default system path of this app - we will then overwrite this with the database from the server
db.close();
OutputStream os = null;
InputStream is = null;
try{
is = ctx.getAssets().open(databaseName+".db");
os = new FileOutputStream("/data/data/com.DemoSqlite/databases/"+databaseName+".db");
copyFile(os, is);
}catch (Exception e) {
Log.e("DB", "Database not found", e);
}finally{
try{
if(os != null)
os.close();
if(is != null)
is.close();
} catch (IOException e) {Log.e("DB", "Can't close adapters");}
}
}
private void copyFile(OutputStream os, InputStream is) throws IOException {
byte[] buffer = new byte[1024];
int length;
while((length = is.read(buffer))>0)
os.write(buffer, 0, length);
os.flush();
}
}
我的代码有什么问题?
谢谢