项目中要使用数据库,考虑用greendao,正常接入。
GreenDao配置
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0'
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao'
greendao {
schemaVersion 1//数据库版本号
daoPackage 'com.xiaoyehai.landsurvey.greendao'//设置DaoMaster、DaoSession、Dao包名
targetGenDir 'src/main/java'//设置DaoMaster、DaoSession、Dao目录
}
implementation 'org.greenrobot:greendao:3.2.2'
实体类
public class TestEntity {
@Id
public Long id;
public String name;
public String age;
public String number;
public String score;
}
初始化:
public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
//初始化数据库
DbCore.init(this);
//DbCore是我写的一个工具类
}
}
Ui 中调用:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TestEntityDao testEntityDao = DbCore.getDaoSession().getTestEntityDao();
TestEntity testEntity = new TestEntity(1L,"222","13","11","22");
testEntityDao.insert(testEntity);
List<TestEntity> list = testEntityDao.loadAll();
Log.e("-------------",list.get(0).getAge());
}
}
直接报错如题。然后上网找了教程,试了别人的demo,一个尿性,统统阵亡。
最后在必应 搜到答案:
implementation 'org.greenrobot:greendao:3.2.2'
//必须加,不然会报错
implementation 'net.zetetic:android-database-sqlcipher:3.5.4@aar'
添加这个三方库,这个库的作用是加密,提高安全性。
但如果你不在乎数据库的安全问题,那末请把
调用getWritableDatabase()方法获取未加密的SQLiteDatabase,如果我们需要做加密,只需要调getEncryptedWritableDb()方法获取加密的Database就可以
好在问题解决,记录一下。