工作空间里的Grable
dependencies {
classpath 'com.android.tools.build:gradle:3.2.0'
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin
}
//app里的Gradle里的跟目录
apply plugin: 'org.greenrobot.greendao' // apply plugin
greendao {
schemaVersion 1 //数据库版本号
daoPackage 'com.example.zhoukao1_model.gen'
// 设置DaoMaster、DaoSession、Dao 包名
targetGenDir 'src/main/java'//设置DaoMaster、DaoSession、Dao目录
generateTests false //设置为true以自动生成单元测试。
targetGenDirTests 'src/main/java' //应存储生成的单元测试的基本目录。默认为 src / androidTest / java。
}
导依赖
//greenDao
implementation 'org.greenrobot:greendao:3.2.2' // add library
创建数据库中的属性类----ShopData
@Entity
类(){
@Id(autoincrement = true)
@Unique
@Property(nameInDb="commodityId")
public long commodityId;
public String commodityName;
public String masterPic;
public String price;
}
锤子锤他
创建GreenDaoUtils类
public class GreenDaoUtils {
public static void initGreenDao(Context context) {
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, "shopdata.db");
SQLiteDatabase db = helper.getWritableDatabase();
DaoMaster daoMaster = new DaoMaster(db);
daoSession = daoMaster.newSession();
}
private static DaoSession daoSession;
public DaoSession getDaoSession() {
return daoSession;
}
}
Application类中初始化
GreenDaoUtils.initGreenDao(this);
添加数据
ShopData shopData = new ShopData();
for (ShopBean.shopData Data : shopBean.result) {
shopData.setCommodityId(Long.parseLong(Data.commodityId));
shopData.setCommodityName(Data.commodityName);
shopData.setMasterPic(Data.masterPic);
shopData.setPrice(Data.price);
}
ShopDataDao shopDataDao = new GreenDaoUtils().getDaoSession().getShopDataDao();
shopDataDao.insert(shopData);