This article refers to the simple use of A Dui's Green Dao 3.2 article: https://www.cnblogs.com/wjtaigwh/p/6394288.html
During this period of preparation, I have been preparing some technical points that need to be used in the reconstruction of old projects. One of them is the use of databases. I have consulted relevant materials and got familiar with the main points of using GreenDao data.
1. GreenDao's features, such as fast response, small dependence on packages, are not much to say here. Partners who have heard of this database solution should know. 2. Here we talk about his other advantages: easy integration and easy use.
1. Integrating GreenDao database:
1,In Engineering App Of gradle The following is added: apply plugin: 'org.greenrobot.greendao'; 2,In Engineering App Of gradle Lower dependencies Adding dependencies: compile 'org.greenrobot:greendao:3.2.0'; 3,In Engineering App Of gradle Lower android{}Add inside GreenDao Version number of database: greendao { //Version number, configurable for upgrade schemaVersion 1 daoPackage 'com.haoyue.greendao' targetGenDir 'src/main/java' }
schemaVersion must be added to update the database iteratively in the future; daoPackage and targetGenDir are candidates to specify where the generated GreenDao java files are stored.
App's gradle integration is complete, and now we're starting to integrate gradle under Moudle:
1. Add classpath'org.green robot: greendao-gradle-plugin: 3.2.1'under dependencies 2. Add in repositories: maven {url "https://maven.google.com"};
The gradle under Moudle is as follows:
buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.3.3' classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { jcenter() maven { url "https://maven.google.com" } } } task clean(type: Delete) { delete rootProject.buildDir }
So far, GreenDao's dependency integration is complete.
Create Bean files for objects we want to save:
@Entity public class ShopBean { public static final int SHOPCART = 0x001; public static final int COLLECTION = 0x002; //Id denotes the primary key and the primary key cannot use int;autoincrement=true denotes the primary key Id self-increasing @org.greenrobot.greendao.annotation.Id(autoincrement = true) private Long Id; //Commodity name (unique means that the attribute must be unique in the database) @Unique private String name; //commodity price private String price; //Quantity sold private int sellNumber; //Icon address private String imageUrl; //Merchant address private String merchantAddress; //Categorization of Lists of Commodities private int type; }
Here is a brief description of the object annotations in ShopBean:
1. @Entity: Change our common java class into an entity class that can be recognized by green DAO. 2. @Id corresponds to the Id field in the data table, which is the unique identification of a data. 3. The @Property(nameInDb = STUDENTNUM) table name corresponds to the STUDENTNUM field in the data table. 4. @NotNull: Make this attribute a "NOT NULL" column on the database side. It is usually meaningful to mark the original type (long, int, short, byte) with @NotNull. 5. @Transient: Indicates that this field will not be written to the database, but will be used as a common java class field to temporarily store data and will not be persisted. 6. @Property can customize field names. Note that foreign keys cannot use this property 7. @Unique table name This property can only have unique values in the database
Of the above seven items, 1 and 2 are necessary and cannot be omitted, otherwise database tables will fail to be created. The remaining options are added as needed.
3. Click Make Project in Build, Android Studio will automatically generate the Getter and Setter methods of variables, as well as the parametric and non-parametric construction methods. At the same time, DaoMaster. java, DaoSession. Java and ShopBeanDao. Java will be generated under the file package we specify (src/main/java/com.haoyue.greendao). These three files will help us conveniently. Operate the database, but we don't need to operate on it or change it.
4. Edit Utils files of operation database.
About this part, some partners write several parts, one part is the DaoManager file, which is used to create the database, create database tables, include the operation of add, delete, check and upgrade the database. The other part is the Utils file that operates the database. Here I write both in the same file. Specifically as follows:
public class GreenDaoUtils { public static final String SHOP_DB_Name = "ShopBean.db"; public static DaoSession sDaoSession; public static DaoMaster.DevOpenHelper helper; public static DaoMaster master; public static GreenDaoUtils instance; public static Context sContext; public static GreenDaoUtils getInstance(){ if(instance == null){ synchronized (GreenDaoUtils.class){ if(instance == null){ instance = new GreenDaoUtils(); } } } return instance; } public void init(Context context){ sContext = context; } public void setUpdataBase(){ //Create the database shop.db helper = new DaoMaster.DevOpenHelper(sContext, SHOP_DB_Name, null); //Getting Writable Database SQLiteDatabase db = helper.getWritableDatabase(); //Getting database objects master = new DaoMaster(db); //Getting dao Object Manager sDaoSession = master.newSession(); } //Open Print Log public void initLogInfo(){ QueryBuilder.LOG_SQL = true; QueryBuilder.LOG_VALUES = true; } //Close the database. Called in the onDestroy method. (Calling this method throws an IllegalStateException exception) public void closedDb(){ if(helper != null){ helper.close(); helper = null; } if(sDaoSession != null){ sDaoSession.clear(); sDaoSession = null; } } /** Insert individual data * getShopDao().insert(shop); * getShopDao().insertOrReplace(shop); */ public boolean insertOne(ShopBean shop){ boolean insertFlag = sDaoSession.getShopBeanDao().insert(shop) == -1 ? false : true; return insertFlag; } public boolean insertOrReplaceOne(ShopBean shopBean){ boolean insertOrReplaceFlag = sDaoSession.getShopBeanDao().insertOrReplace(shopBean) == -1 ? false : true; return insertOrReplaceFlag; } /** Insert multiple data * getShopDao().insertInTx(shopList); * getShopDao().insertOrReplaceInTx(shopList); */ public boolean insertManyData(List<ShopBean> shopList){ boolean insertManyFlag = false; try{ sDaoSession.getShopBeanDao().insertInTx(shopList); insertManyFlag = true; }catch (Exception e){ Log.i("TAG", "insertManyData: e.printStackTrace()" + e); } return insertManyFlag; } public boolean insertInTxManyData(List<ShopBean> shopList){ boolean insertInTxFlag = false; try { sDaoSession.getShopBeanDao().insertOrReplaceInTx(shopList); insertInTxFlag = true; }catch (Exception e){ Log.i("TAG", "insertInTxManyData: e.printStackTrace()" + e); } return insertInTxFlag; } /** Query all * List< Shop> list = getShopDao().loadAll(); * List< Shop> list = getShopDao().queryBuilder().list(); */ public List<ShopBean> querryAll(){ List<ShopBean> list = new ArrayList<>(); try{ list = sDaoSession.getShopBeanDao().loadAll(); Log.i("TAG", "queryBuilder The length of the queried data list.size() ==" + list.size()); }catch (Exception e){ Log.i("TAG", "querryAll: e.printStackTrace()" + e); } return list; } public List<ShopBean> queryBuilder(){ List<ShopBean> list = new ArrayList<>(); try{ list = sDaoSession.getShopBeanDao().queryBuilder().list(); Log.i("TAG", "queryBuilder The length of the queried data list.size() ==" + list.size()); }catch (Exception e){ Log.i("TAG", "queryBuilder: e.printStackTrace()" + e); } return list; } /** Total number of queries * .count() */ public long querryCount(){ long count = 0; try{ count = sDaoSession.getShopBeanDao().count(); Log.i("TAG", "querryCount Total number of queries count ==" + count); }catch (Exception e){ Log.i("TAG", "querryCount: e.printStackTrace()" + e); } return count; } /** * Modify individual data * getShopDao().update(shop); */ public boolean updateOneData(ShopBean shop){ boolean updateOneFlag = false; try{ sDaoSession.getShopBeanDao().update(shop); updateOneFlag = true; }catch (Exception e){ Log.i("TAG", "updateOneData: e.printStackTrace()" + e); } return updateOneFlag; } /** * Modify multiple data * getShopDao().updateInTx(shopList); */ public boolean updateList(List<ShopBean> list){ boolean updateListFlag = false; try{ sDaoSession.getShopBeanDao().updateInTx(list); updateListFlag = true; }catch (Exception e){ Log.i("TAG", "updateList: e.printStackTrace()" + e); } return updateListFlag; } /** * Delete individual data * getTABUserDao().delete(user); */ public boolean deleteOneData(ShopBean shop){ boolean deleteOneFlag = false; try{ sDaoSession.getShopBeanDao().delete(shop); deleteOneFlag = true; }catch (Exception e){ Log.i("TAG", "deleteOneData: e.printStackTrace()" + e); } return deleteOneFlag; } /** * Delete multiple data * getUserDao().deleteInTx(userList); */ public boolean deleteDataList(List<ShopBean> list){ boolean deleteDataFlag = false; try{ sDaoSession.getShopBeanDao().deleteInTx(list); deleteDataFlag = true; }catch (Exception e){ Log.i("TAG", "deleteDataList: e.printStackTrace()" + e); } return deleteDataFlag; } /** * Delete all */ public boolean deleteAll(){ boolean deleteAllFlag = false; try{ sDaoSession.getShopBeanDao().deleteAll(); deleteAllFlag = true; }catch (Exception e){ Log.i("TAG", "deleteAll: e.printStackTrace()" + e); } return deleteAllFlag; } /** * Delete a Key value */ public boolean deleteByKey(Long key){ boolean deleteByKeyFlag = false; try{ sDaoSession.getShopBeanDao().deleteByKey(key); deleteByKeyFlag = true; }catch (Exception e){ Log.i("TAG", "deleteByKey: e.printStackTrace()" + e); } return deleteByKeyFlag; } /** * Delete in batches according to Key */ public boolean deleteByKeyList(List<Long> list){ boolean deleteByKeyListFlag = false; try{ sDaoSession.getShopBeanDao().deleteByKeyInTx(list); deleteByKeyListFlag = true; }catch (Exception e){ Log.i("TAG", "deleteByKeyList: e.printStackTrace()" + e); } return deleteByKeyListFlag; } }
When using, in Activity, the GreenDaoUtils object is obtained in the onCreate method first:
mDaoUtils = GreenDaoUtils.getInstance();//Getting Utils objects
Then the following methods are invoked in turn:
mDaoUtils .init(this);//Instance registration mDaoUtils .setUpdataBase();//Database Creation mDaoUtils .initLogInfo();//Log Printing Switch
Then you can start the operation of the database.
Let's first experience the effect:
1. Primitive state:
private void initData() { mShopBeanList = mDaoUtils.querryAll(); if (mShopBeanList == null || mShopBeanList.size() <= 0) { mShopBeanList = mDaoUtils.queryBuilder(); if (mShopBeanList == null || mShopBeanList.size() <= 0) { for (int i = 0; i < 6; i++) { ShopBean shop = new ShopBean(); shop.setId(null); shop.setName(name[i]); shop.setPrice((i + 15) * 133 / 28 + ""); shop.setSellNumber((i + 10) * 359); shop.setImageUrl(imageUrl[i]); int mod = i % 2; shop.setMerchantAddress(address[mod]); if (mod == 1) { shop.setType(ShopBean.COLLECTION); } else if (mod == 0) { shop.setType(ShopBean.SHOPCART); } mShopBeanList.add(shop); } } } mDaoAdapter = new GreenDaoAdapter(GreenDaoActivity.this, mShopBeanList); FullyLinearLayoutManager layoutManager = new FullyLinearLayoutManager(GreenDaoActivity.this); layoutManager.setOrientation(LinearLayoutManager.VERTICAL); mRvGreenDao.setLayoutManager(layoutManager); mRvGreenDao.addItemDecoration(new RecycleViewDividerSegmentate(this, LinearLayoutManager.VERTICAL)); mRvGreenDao.setAdapter(mDaoAdapter); }
2. Insert a single data insertOne and insertOrReplaceOne, both of which perform the same result:
private void insertOne(){ ShopBean insertOne = new ShopBean(); insertOne.setId(null); insertOne.setName("btinsertOne"); insertOne.setPrice("¥208"); insertOne.setSellNumber(37958); insertOne.setImageUrl(imageUrl[6]); insertOne.setMerchantAddress(address[1]); insertOne.setType(ShopBean.SHOPCART); mDaoUtils.insertOne(insertOne); mShopBeanList = mDaoUtils.querryAll(); mDaoAdapter.refreshData(mShopBeanList); }
!
private void insertOrReplaceOne(){ ShopBean insertOrReplace = new ShopBean(); insertOrReplace.setId(null); insertOrReplace.setName("btinsertOrReplaceOne"); insertOrReplace.setPrice("¥208"); insertOrReplace.setSellNumber(37958); insertOrReplace.setImageUrl(imageUrl[6]); insertOrReplace.setMerchantAddress(address[1]); insertOrReplace.setType(ShopBean.SHOPCART); mShopBeanList = mDaoUtils.querryAll(); mDaoAdapter.refreshData(mShopBeanList); }
3. Batch insert data insertManyData and insertInTxManyData:
private void insertManyData(){ for (int i = 0; i < 6; i++) { ShopBean shop = new ShopBean(); shop.setId(null); shop.setName(address[2] + "**" + name[i]); shop.setPrice((i + 15) * 1330 + ""); shop.setSellNumber((i + 10) * 3590); shop.setImageUrl(imageUrl[i]); int mod = i % 2; shop.setMerchantAddress(address[2]); if (mod == 1) { shop.setType(ShopBean.COLLECTION); } else if (mod == 0) { shop.setType(ShopBean.SHOPCART); } mShopBeanList.add(shop); } mDaoUtils.insertManyData(mShopBeanList); mShopBeanList = mDaoUtils.querryAll(); mDaoAdapter.refreshData(mShopBeanList); }
The insertManyData method is invalid when it is executed and the data insertion fails. The insertInTxManyData can be successfully inserted into the data.
private void insertInTxManyData(){ for (int i = 0; i < 6; i++) { ShopBean shop = new ShopBean(); shop.setId(null); shop.setName(address[2] + "*||||||*" + name[i]); shop.setPrice((i + 15) * 1330 + ""); shop.setSellNumber((i + 10) * 3590); shop.setImageUrl(imageUrl[i]); int mod = i % 2; shop.setMerchantAddress(address[2]); if (mod == 1) { shop.setType(ShopBean.COLLECTION); } else if (mod == 0) { shop.setType(ShopBean.SHOPCART); } mShopBeanList.add(shop); } mDaoUtils.insertInTxManyData(mShopBeanList); mShopBeanList = mDaoUtils.querryAll(); mDaoAdapter.refreshData(mShopBeanList); }
4. Query all data queryBuilder and querryAll:
Log.i("TAG", "querryAll().size ===" + mDaoUtils.querryAll().size()); Log.i("TAG", "queryBuilder().size ===" + mDaoUtils.queryBuilder().size());
5. Query the total amount of database data querryCount:
Log.i("TAG", "qquerryCount ===" + mDaoUtils.querryCount());
6. Update single data updateOne Data:
private void updateOneData(){ //Get the data object to update ShopBean shopBean = mShopBeanList.get(0); //Setting Updated Contents shopBean.setName("Aquatic duckweed"); //Update data set boolean updateOneFlag = mDaoUtils.updateOneData(shopBean); //Get all the updated data and load it out mShopBeanList = mDaoUtils.querryAll(); mDaoAdapter.refreshData(mShopBeanList); }
7. Update List for batch update data:
private void updateList(){ //Get the data object to update ShopBean shopBean1 = mShopBeanList.get(1); ShopBean shopBean2 = mShopBeanList.get(2); ShopBean shopBean3 = mShopBeanList.get(3); //Setting Updated Contents shopBean1.setName("Cute"); shopBean2.setName("Gong Ben Chu Si"); shopBean3.setName("Sword none"); List<ShopBean> updateList = new ArrayList<>(); updateList.add(shopBean1); updateList.add(shopBean2); updateList.add(shopBean3); //Update data set boolean updateListFlag = mDaoUtils.updateList(updateList); //Get all the updated data and load it out mShopBeanList = mDaoUtils.querryAll(); mDaoAdapter.refreshData(mShopBeanList); }
8. Batch delete data deleteDataList:
private void deleteDataList(){ //Get the data object to delete ShopBean deleteList01 = mShopBeanList.get(6); ShopBean deleteList02 = mShopBeanList.get(7); List<ShopBean> deleteList = new ArrayList<>(); deleteList.add(deleteList01); deleteList.add(deleteList02); //Delete data sets boolean deleteLstFlag = mDaoUtils.deleteDataList(deleteList); //Query all remaining data after deletion and load it out mShopBeanList = mDaoUtils.querryAll(); mDaoAdapter.refreshData(mShopBeanList); }
9. Delete a data deleteOne Data:
private void deleteOneData(){ //Get the last piece of data ShopBean deleteOne = mShopBeanList.get((int) mDaoUtils.querryCount() - 1); //Delete the last data boolean deleteOneFlag = mDaoUtils.deleteOneData(deleteOne); //Query all remaining data after deletion and load it out mShopBeanList = mDaoUtils.querryAll(); mDaoAdapter.refreshData(mShopBeanList); }
10. Delete all data deleteAll: After this method is executed, all data will be deleted
boolean deleteAllFlag = mDaoUtils.deleteAll();