SQLite:Android中“没有这样的表”

时间:2019-05-20 10:30:54

标签: android sqlite android-sqlite

我一直在在线上学习教程,以为我的项目学习SQLite,但是我的应用程序因表不存在的错误而不断崩溃。但是,当我使用SQLite Manager查看数据库时,该数据库存在。

这是我的代码

public class SQLiteDbHelper extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "mybook";
private static final String DB_PATH_SUFFIX = "/databases";
static Context mCtx;

SQLiteDbHelper(Context context){
    super(context,DATABASE_NAME,null,DATABASE_VERSION);
    mCtx = context;
}

public ArrayList<Model> getDetails(){
    SQLiteDatabase db = this.getReadableDatabase();
    ArrayList<Model> modelList = new ArrayList<>();

    //crash occurs here
    Cursor cursor = db.rawQuery("SELECT * FROM booktable",null);
    if (cursor!=null){
        while (cursor.moveToNext()){
            Model count = new Model(cursor.getInt(0),cursor.getString(1),cursor.getString(2));
            modelList.add(count);
        }
        cursor.close();
        db.close();
    }
    return modelList;
}

public void CopyDatabaseFromAssests() throws IOException{
    InputStream myInput = mCtx.getAssets().open(DATABASE_NAME);
    String outFile = getDatabasePath();

    File f = new File(mCtx.getApplicationInfo().dataDir + DB_PATH_SUFFIX);
    if (!f.exists())
        f.mkdir();

    OutputStream myOutPut = new FileOutputStream(outFile);

    byte[] buffer = new byte[1024];
    int lenght;
    while ((lenght = myInput.read(buffer))>0){
        myOutPut.write(buffer,0,lenght);
    }
    myOutPut.flush();
    myOutPut.close();
    myInput.close();
}

private static String getDatabasePath() {
    return mCtx.getApplicationInfo().dataDir + DB_PATH_SUFFIX
            + DATABASE_NAME;
}

public SQLiteDatabase openDatabase() throws SQLiteException{
    File dbFile = mCtx.getDatabasePath(DATABASE_NAME);
    if (!dbFile.exists()){
        try {
            CopyDatabaseFromAssests();
            Toast.makeText(mCtx,"copied from assest",Toast.LENGTH_LONG).show();
        }catch (IOException e){
            throw new RuntimeException("error occured",e);
        }
    }
    return SQLiteDatabase.openDatabase(dbFile.getPath(),null,SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase
    .CREATE_IF_NECESSARY);
}

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {

}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

 }
}

这是我第一次使用SQLite数据库。

1 个答案:

答案 0 :(得分:0)

您必须在onCreate方法旁边编写表创建代码,

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {

 sqLiteDatabase.execSQL("create table "+DataBaseConstants.TABLE_NAME_APPCONFIG + "(id integer primary key AUTOINCREMENT, responseData text NOT NULL,createdDate text NOT NULL)");

}

,并且必须写在onUpgrade方法上,该方法用于比较您的先前版本和当前数据库版本,并根据,

更新表
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    if (oldVersion < newVersion) {
        db.execSQL("DROP TABLE " + "write your table name here");
        onCreate(db);
    }
}