GreenDao Database: use the database files and databases in the Raw folder to upgrade greendaoraw.

Source: Internet
Author: User

GreenDao Database: use the database files and databases in the Raw folder to upgrade greendaoraw.
1. Use the database files in the Raw folder

When using the GreenDao framework, databases and data tables are automatically created based on the generated framework code. The OpenHelper class in the generated DaoMaster shows that:

Public static abstract class OpenHelper extends SQLiteOpenHelper {public OpenHelper (Context context, String name, CursorFactory factory) {super (context, name, factory, SCHEMA_VERSION );} @ Override public void onCreate (SQLiteDatabase db) {Log. I ("greenDAO", "Creating tables for schema version" + SCHEMA_VERSION );
// Modify the second parameter to true.
CreateAllTables (db, false );}}

Code of the corresponding createAllTables function:

/** Creates underlying database table using DAOs. */    public static void createAllTables(SQLiteDatabase db, boolean ifNotExists) {        xxxxxDao.createTable(db, ifNotExists);    }

Next, let's look at the following:

/** Creates the underlying database table. */    public static void createTable(SQLiteDatabase db, boolean ifNotExists) {        String constraint = ifNotExists? "IF NOT EXISTS ": "";        db.execSQL("CREATE TABLE " + constraint + "'DOCTOR' (" + //                "'_id' INTEGER PRIMARY KEY AUTOINCREMENT ," + // 0: id                "'NAME' TEXT," + // 1: name                   }

From the code above, we can see that GreenDao will force the creation of data tables when it is used for the first time. If this happens, the program may crash.

Public static abstract class OpenHelper extends SQLiteOpenHelper {public OpenHelper (Context context, String name, CursorFactory factory) {super (context, name, factory, SCHEMA_VERSION );} @ Override public void onCreate (SQLiteDatabase db) {Log. I ("greenDAO", "Creating tables for schema version" + SCHEMA_VERSION); // modify the second parameter to true createAllTables (db, true );}}

To use the database files in Raw files, take the following steps:

1) Modify parameters:

Public static abstract class OpenHelper extends SQLiteOpenHelper {public OpenHelper (Context context, String name, CursorFactory factory) {super (context, name, factory, SCHEMA_VERSION );} @ Override public void onCreate (SQLiteDatabase db) {Log. I ("greenDAO", "Creating tables for schema version" + SCHEMA_VERSION); // modify the second parameter to true createAllTables (db,True);}}

2) Add the GreenDaoContextWrapper. java file to the project.

public class GreenDaoContextWrapper extends ContextWrapper {

private Context mContext;

public GreenDaoContextWrapper(Context base) {
super(base);
this.mContext= base;
}

@Override
public File getDatabasePath(String name) {
Log.d("GreenDao","getDatabasePath");
Log.d("GreenDao",mContext.getDatabasePath(name).getAbsolutePath());
String filePath=mContext.getDatabasePath(name).getAbsolutePath();
File file=new File(filePath);
if (!file.exists()){
buildDatabase(filePath);
}
return file;
}
  
/**
* To create a database file, copy the database file in the raw folder to the database folder of the application:
*/Data/com. xxxx/databases/
* @ Param filePath
*/

Private void buildDatabase (String filePath ){
        Log.d("GreenDao","buildDatabase");
InputStream inputStream=mContext.getResources().openRawResource(R.raw.accurmedicine);
FileOutputStream fos= null;
try {
fos = new FileOutputStream(filePath);
byte[] buffer=new byte[1024];
int length;
while ((length=inputStream.read(buffer))>0){
fos.write(buffer,0,length);
}
fos.close();
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}

@Override
public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory) {
Log.d("GreenDao","openOrCreateDatabase");
SQLiteDatabase result= SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name),factory);
return result;
}

@Override
public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler) {
Log.d("GreenDao","openOrCreateDatabase");
SQLiteDatabase result= SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name),factory);
return result;
}
}

ContextWrapper is a Context package class and must contain a real Context. For details, see:

Http://www.jianshu.com/p/94e0f9ab3f1d

3) Use GreenDaoContextWrapper when creating DevOpenHelper

String DBName="xxx";DaoMaster.DevOpenHelper helper=new DaoMaster.DevOpenHelper(new GreenDaoContextWrapper(context),DBName,null);

This is all done!

 

Ii. Database Version Upgrade

This method is shown on the Internet. If it is good, it will be moved.

Public class MigrationHelper {private static MigrationHelper instance; public static MigrationHelper getInstance () {if (instance = null) {instance = new MigrationHelper ();} return instance ;} /*** create temporary table> delete old table> Create new table> import data * @ param database * @ param daoClasses */public void migrate (SQLiteDatabase database, Class <? Extends AbstractDao <?,?>... DaoClasses) {generateTempTables (database, daoClasses); DaoMaster. dropAllTables (database, true); DaoMaster. createAllTables (database, false); restoreData (database, daoClasses);}/*** temporary table Production * @ param database * @ param daoClasses */private void generateTempTables (SQLiteDatabase database, class <? Extends AbstractDao <?,?>... DaoClasses) {for (int I = 0; I <daoClasses. length; I ++) {DaoConfig config = new DaoConfig (database, daoClasses [I]); String divider = ""; String tableName = config. tablename; String tmpTableName = config. tablename. concat ("_ TEMP"); ArrayList <String> properties = new ArrayList <> (); StringBuilder createTableStringBuilder = new StringBuilder (); createTableStringBuilder. append ("create table "). append (tmpTableName ). append ("("); List <String> columns = getColumns (database, tableName); for (int j = 0; j <config. properties. length; j ++) {String columnName = config. properties [j]. columnName; if (columns. contains (columnName) {properties. add (columnName); String type = null; try {type = getTypeByClass (config. properties [j]. type);} catch (Exception e) {e. printStackTrace ();} createTableStringBuilder. append (divider ). append (columnNam E ). append (""). append (type); if (config. properties [j]. primaryKey) {createTableStringBuilder. append ("primary key") ;}divider = "," ;}} createTableStringBuilder. append (");"); Log. d ("xxxxx", "SQL =" + createTableStringBuilder. toString (); database.exe cSQL (createTableStringBuilder. toString (); StringBuilder insertTableString = new StringBuilder (); insertTableString. append ("insert "). append (tmpTableNam E ). append ("("); insertTableString. append (TextUtils. join (",", properties); insertTableString. append (") select"); insertTableString. append (TextUtils. join (",", properties); insertTableString. append ("from "). append (tableName ). append (";"); Log. d ("xxxxx", "SQL =" + insertTableString. toString (); database.exe cSQL (insertTableString. toString () ;}}/*** The data field matches the Java data type * @ param type * @ return * @ throws Ex Ception */private String getTypeByClass (Class <?> Type) throws Exception {if (type. equals (String. class) {return "TEXT";} if (type. equals (Long. class) | type. equals (Integer. class) {return "INTEGER";} if (type. equals (Boolean. class) {return "BOOLEAN";} String strException = "data table data type matching error"; Exception exception = new Exception (strException. concat ("-Class "). concat (type. toString (); throw exception;}/*** get the field list of the current data table * @ param database * @ param table Name * @ return */private static List <String> getColumns (SQLiteDatabase database, String tableName) {List <String> columns = new ArrayList <> (); Cursor cursor = null; /*** query the data table */cursor = database. rawQuery ("select * from" + tableName + "limit 1", null); try {if (cursor! = Null) {String [] columnNames = cursor. getColumnNames (); for (String name: columnNames) {columns. add (name. toUpperCase ();} // columns = new ArrayList <> (Arrays. asList (cursor. getColumnNames ();} catch (Exception e) {e. printStackTrace ();} finally {if (cursor! = Null) {cursor. close () ;}} return columns;}/*** data recovery-> delete a temporary table * @ param database * @ param daoClasses */private void restoreData (SQLiteDatabase database, Class <? Extends AbstractDao <?,?>... DaoClasses) {for (int I = 0; I <daoClasses. length; I ++) {DaoConfig config = new DaoConfig (database, daoClasses [I]); String tableName = config. tablename; String tmpTableName = config. tablename. concat ("_ TEMP"); ArrayList <String> properties = new ArrayList <> (); for (int j = 0; j <config. properties. length; j ++) {String columnName = config. properties [j]. columnName; if (getColumns (database, tmpTableName ). contains (columnName) {properties. add (columnName) ;}} StringBuilder insertTableStringBuilder = new StringBuilder (); insertTableStringBuilder. append ("insert "). append (tableName ). append ("("); insertTableStringBuilder. append (TextUtils. join (",", properties); insertTableStringBuilder. append (") SELECT"); insertTableStringBuilder. append (TextUtils. join (",", properties); insertTableStringBuilder. append ("FROM "). append (tmpTableName ). append (";"); StringBuilder dropTableStringBuilder = new StringBuilder (); dropTableStringBuilder. append ("drop table "). append (tmpTableName); database.exe cSQL (insertTableStringBuilder. toString (); database.exe cSQL (dropTableStringBuilder. toString ());}}}

 

Then modifySCHEMA_VERSION

 

public static final int SCHEMA_VERSION = 1;

This variable is used to specify the database version number when creating OpenHelper.

Then modify the onUpgrade code of DevOpenHelper:

 @Override        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {            Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion + " by dropping all tables");//            dropAllTables(db, true);//            onCreate(db);            MigrationHelper.getInstance()                    .migrate(db,                    paramsDao.class,                    );        }

The final success!

To view the SQLite database version, run the following statement:

 

PRAGMA user_version

 

Set the SQLite database version statement:

PRAGMA user_version = <your version number>

The above two sentences can be seen in the source code of SQLiteDatabase and SQLiteOpenHelper:

In the SQLiteOpenHelper source code of android-24, you can see:

/**     * Gets the database version.     *     * @return the database version     */    public int getVersion() {        return ((Long) DatabaseUtils.longForQuery(this, "PRAGMA user_version;", null)).intValue();    }    /**     * Sets the database version.     *     * @param version the new database version     */    public void setVersion(int version) {        execSQL("PRAGMA user_version = " + version);    }

SQLiteOpenHelper is implemented by calling these two statements to set and obtain the database version. For specific source code, you can view the getDatabaseLocked function of SQLiteOpenHelper, which will not be described here.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.