尝试从Assets文件夹访问Sqlite数据库时出错

时间:2018-03-11 16:56:52

标签: android sqlite

这是我的DatabaseHelper,我正在尝试连接到我的数据库文件(db.sql):

public class DatabaseHelper extends SQLiteOpenHelper {

private final static String TAG = "DatabaseHelper";
private final Context myContext;
private static final String DATABASE_NAME = "db.sql";
private static final int DATABASE_VERSION = 1;
private String pathToSaveDBFile;

public DatabaseHelper(Context context, String filePath) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    this.myContext = context;
    pathToSaveDBFile = new StringBuffer(filePath).append("/").append(DATABASE_NAME).toString();
}

public void prepareDatabase() throws IOException {
    boolean dbExist = checkDataBase();
    if(dbExist) {
        Log.d(TAG, "Database exists.");
        int currentDBVersion = 1;
        if (DATABASE_VERSION > currentDBVersion) {
            Log.d(TAG, "Database version is higher than old.");
            deleteDb();
            try {
                copyDataBase();
            } catch (IOException e) {
                Log.e(TAG, e.getMessage());
            }
        }
    } else {
        try {
            copyDataBase();
        } catch (IOException e) {
            Log.e(TAG, e.getMessage());
        }
    }
}

private boolean checkDataBase() {
    boolean checkDB = false;
    try {
        File file = new File(pathToSaveDBFile);
        checkDB = file.exists();
    } catch(SQLiteException e) {
        Log.d(TAG, e.getMessage());
    }
    return checkDB;
}

private void copyDataBase() throws IOException {
    OutputStream os = new FileOutputStream(pathToSaveDBFile);
    InputStream is = myContext.getAssets().open("sqlite/"+DATABASE_NAME);
    byte[] buffer = new byte[1024];
    int length;
    while ((length = is.read(buffer)) > 0) {
        os.write(buffer, 0, length);
    }
    is.close();
    os.flush();
    os.close();
}

public void deleteDb() {
    File file = new File(pathToSaveDBFile);
    if(file.exists()) {
        file.delete();
        Log.d(TAG, "Database deleted.");
    }
}
@Override
public void onCreate(SQLiteDatabase db) {
    Log.d(TAG, "onCreate");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    if (newVersion > oldVersion)
    {
        Log.v("Database Upgrade", "Database version higher than old.");
        deleteDb();
    }
}

public List<Office> getOffices() {
    SQLiteDatabase db = SQLiteDatabase.openDatabase(pathToSaveDBFile, null, SQLiteDatabase.OPEN_READONLY);
    String query = "SELECT ID, NAME, IMG , LOCATION FROM Offices";
    Cursor cursor = db.rawQuery(query, null);
    List<Office> list = new ArrayList<Office>();

    while(cursor.moveToNext()) {
        Office office = new Office();
        office.setOfficeID(cursor.getInt(0));
        office.setOfficeName(cursor.getString(1));
        office.setOfficeImg(cursor.getInt(2));
        office.setOfficeLocation(cursor.getString(3));
        list.add(office);
    }
    db.close();
    return  list;
}}

我的数据库包含一个表(办公室),其中包含四行:ID,名称,图像和位置。

当我在午餐时,应用程序崩溃,我收到错误“没有这样的表:办公室” 我试图从Stackoverflow的其他答案中解决错误,但不幸的是没有任何作用,仍然有相同的错误。

这是跟踪轨迹:

03-11 16:39:32.872 4352-4352/com.artline.ministryoftourismpalestine E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                  Process: com.artline.ministryoftourismpalestine, PID: 4352
                                                                                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.artline.ministryoftourismpalestine/com.artline.ministryoftourismpalestine.Offices}: android.database.sqlite.SQLiteException: no such table: Offices (code 1): , while compiling: SELECT ID, NAME, IMG , LOCATION FROM Offices
                                                                                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
                                                                                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
                                                                                      at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
                                                                                      at android.os.Handler.dispatchMessage(Handler.java:106)
                                                                                      at android.os.Looper.loop(Looper.java:164)
                                                                                      at android.app.ActivityThread.main(ActivityThread.java:6494)
                                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                                      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
                                                                                   Caused by: android.database.sqlite.SQLiteException: no such table: Offices (code 1): , while compiling: SELECT ID, NAME, IMG , LOCATION FROM Offices
                                                                                      at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                                      at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:890)
                                                                                      at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:501)
                                                                                      at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                                      at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                                                      at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
                                                                                      at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:46)
                                                                                      at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1392)
                                                                                      at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1331)
                                                                                      at com.artline.ministryoftourismpalestine.DatabaseHelper.getOffices(DatabaseHelper.java:107)
                                                                                      at com.artline.ministryoftourismpalestine.Offices.showData(Offices.java:77)
                                                                                      at com.artline.ministryoftourismpalestine.Offices.onCreate(Offices.java:48)
                                                                                      at android.app.Activity.performCreate(Activity.java:7009)
                                                                                      at android.app.Activity.performCreate(Activity.java:7000)
                                                                                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
                                                                                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
                                                                                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) 
                                                                                      at android.app.ActivityThread.-wrap11(Unknown Source:0) 
                                                                                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) 
                                                                                      at android.os.Handler.dispatchMessage(Handler.java:106) 
                                                                                      at android.os.Looper.loop(Looper.java:164) 
                                                                                      at android.app.ActivityThread.main(ActivityThread.java:6494) 
                                                                                      at java.lang.reflect.Method.invoke(Native Method) 
                                                                                      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
                                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 

请帮我解决错误......

1 个答案:

答案 0 :(得分:0)

您需要将数据库从资产文件夹复制到应用程序内部存储中。然后,您可以从内部存储中读取数据库。

df = pd.DataFrame({
    'value': list(range(10, 19))
})

df = df.reset_index()
       .set_index([df.index % 5, df.index // 5])
       .unstack().sort_index(axis=1, level=1)
df.columns = df.columns.map('{0[0]}_{0[1]}'.format)
print (df)
   index_0  value_0  index_1  value_1
0      0.0     10.0      5.0     15.0
1      1.0     11.0      6.0     16.0
2      2.0     12.0      7.0     17.0
3      3.0     13.0      8.0     18.0
4      4.0     14.0      NaN      NaN