Recently in the project, in order to facilitate the test personnel testing, in the application to add the formal library and test library switching functions. In order to prevent data conflicts between the official library and the test library switchover, the current database must be emptied when switching. The code is as follows:
Package com.example.admin.greendaotest; Import Android.content.context;import Android.database.sqlite.sqlitedatabase;import Com.greendao.gen.daomaster;import Org.greenrobot.greendao.database.Database;/** * Created by admin on 2017/9/19.*/ Public classDBManager {PrivateFinalStaticString DbName ="student_db"; Private StaticDBManager minstance; PrivateDaomaster.openhelper Openhelper; Privatecontext Context; PublicDBManager (Context context) { This. Context =context; Openhelper=NewDaomaster.openhelper (context, DbName,NULL){}; } /** * Get a singleton reference * * @param context * @return*/ Public StaticDBManager getinstance (context context) {if(Minstance = =NULL) {synchronized (DBManager.class) { if(Minstance = =NULL) {minstance=NewDBManager (context); } } } returnminstance; } /** * Get a readable database*/ Privatesqlitedatabase getreadabledatabase () {if(Openhelper = =NULL) {Openhelper=NewMysqliteopenhelper (context, DbName,NULL); } sqlitedatabase DB=openhelper.getreadabledatabase (); returnDB; } /** * Get writable database*/ Privatesqlitedatabase getwritabledatabase () {if(Openhelper = =NULL) {Openhelper=NewMysqliteopenhelper (context, DbName,NULL); } sqlitedatabase DB=openhelper.getwritabledatabase (); returnDB; } Public voidDelesql () {Sqlitedatabase db=getwritabledatabase (); Daomaster Daomaster=Newdaomaster (DB); Daomaster.dropalltables (Daomaster.getdatabase (),true); Daomaster.createalltables (Daomaster.getdatabase (),true); } classMysqliteopenhelper extends daomaster.openhelper{@Override Public voidonCreate (Database db) {super.oncreate (db); } PublicMysqliteopenhelper (Context context, String name, Sqlitedatabase.cursorfactory Factory) {Super (context, NA Me, Factory); } } }
Daomaster must be added. Createalltables (Daomaster.getdatabase (), true), or the database table error is not found when the database operation is re-performed (CRUD): caused by: Android.database.sqlite.SQLiteException:no such table: Table name, as for why the database table is not re-created, I do not know why, in this also wasted some time, so write down this blog.
Android Greendao How to erase a database