转载自:https://www.jianshu.com/p/1044c9cdcc97
package usung.com.n.greendaodemo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import usung.com.n.base.BaseApplicationTwo;
import usung.com.n.R;
import usung.com.n.greendao.UserDao;
import usung.com.n.util.ToastUtil;
/**
* @author fenghui
*/
public class MainActivityextends AppCompatActivity {
private ListViewmListView;
private ListmUserList =null;
private MyAdaptermAdapter;
private UsermUser;
private UserDaomUserDao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = findViewById(R.id.list_view);
loadAllData();
initView();
}
void initView(){
final EditText edtInsert = findViewById(R.id.edt_insert);
final EditText edtDelete = findViewById(R.id.edt_delete);
final EditText edtUpdatet = findViewById(R.id.edt_update);
final EditText edtQureyName = findViewById(R.id.edt_qurey_name);
final EditText edtQureyId = findViewById(R.id.edt_qurey_id);
(findViewById(R.id.insert)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
insert(edtInsert.getText().toString());
}
});
(findViewById(R.id.delete)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
delete(edtDelete.getText().toString());
}
});
(findViewById(R.id.update)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
update(edtUpdatet.getText().toString());
}
});
(findViewById(R.id.qurey)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
qurey(edtQureyId.getText().toString(), edtQureyName.getText().toString());
}
});
(findViewById(R.id.clear)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clear();
}
});
}
/**
* 查询数据库中的所有数据,并显示到适配器上
*/
public void loadAllData(){
mUserDao = BaseApplicationTwo.Companion.getInstance().getDaoSession().getUserDao();
mUserList =mUserDao.loadAll();
if (mUserList ==null){
mUserList =new ArrayList<>();
}
mAdapter =new MyAdapter(this,mUserList);
mListView.setAdapter(mAdapter);
}
/**
* 增
*/
public void insert(String userName){
if (TextUtils.isEmpty(userName)){
ToastUtil.showToast("请输入名称");
return;
}
mUser =new User(null,userName);
mUserDao.insert(mUser);
mAdapter.getmUserList().clear();
mAdapter.getmUserList().addAll(mUserDao.loadAll());
mAdapter.notifyDataSetChanged();
mListView.setSelection(mUserDao.loadAll().size()-1);
}
/**
* 删
* @param id long
*/
public void delete(String id){
if (TextUtils.isEmpty(id)){
ToastUtil.showToast("id不能为空");
return;
}
User findUser =mUserDao.queryBuilder().where(UserDao.Properties.Id.eq(id)).build().unique();
if (findUser !=null){
mAdapter.getmUserList().remove(findUser);
mUserDao.deleteByKey(findUser.getId());
ToastUtil.showToast("删除成功");
}else{
ToastUtil.showToast("用户不存在");
}
mAdapter.notifyDataSetChanged();
}
/**
* 改
*/
public void update(String id){
if (TextUtils.isEmpty(id)){
ToastUtil.showToast("id不能为空");
return;
}
final User findUser =mUserDao.queryBuilder().where(UserDao.Properties.Id.eq(id)).build().unique();
if (findUser !=null){
findUser.setName("fenghui" + findUser.getId());
mUserDao.update(findUser);
ToastUtil.showToast("修改成功");
}else {
ToastUtil.showToast("用户不存在");
return;
}
mUserList =mUserDao.loadAll();
mListView.post(new Runnable() {
@Override
public void run() {
mListView.smoothScrollToPosition(findUser.getId().intValue());
}
});
mAdapter.notifyDataSetChanged();
}
/**
* 查,要么按id查找,要么按照名称查找
*/
public void qurey(String id, String name){
mUserList =mAdapter.getmUserList();
mUserList.clear();
if (TextUtils.isEmpty(id) && TextUtils.isEmpty(name)){
ToastUtil.showToast("请输入查询条件");
mAdapter.getmUserList().addAll(mUserDao.loadAll());
mAdapter.notifyDataSetChanged();
return;
}
if (TextUtils.isEmpty(id)){
mUserList.addAll(mUserDao.queryBuilder().where(UserDao.Properties.Name.eq(name)).build().list());
}else{
mUserList.addAll(mUserDao.queryBuilder().where(UserDao.Properties.Id.eq(id)).build().list());
}
mAdapter.notifyDataSetChanged();
}
/**
* 清空数据库
*/
public void clear() {
mUserDao.deleteAll();
mAdapter.getmUserList().clear();
mAdapter.notifyDataSetChanged();
}
/**
* 跟新ListView,不知为啥adapter.notifyDataSetChanged()没反应
*/
public void notifyListView(){
mUserList.clear();
mUserList =mUserDao.loadAll();
mAdapter =new MyAdapter(MainActivity.this,mUserList);
mListView.setAdapter(mAdapter);
}
}
// BaseApplication
/**
* Descriptions:
* Created by fenghui on 2018/12/25.
*/
class BaseApplicationTwo : Application() {
override fun onCreate() {
super.onCreate()
instance =this
setDatabase()
}
companion object {
private var instance : BaseApplicationTwo? =null
fun getInstance() : BaseApplicationTwo {
return instance!!
}
}
private var db: SQLiteDatabase? =null
private var mDaoMaster:DaoMaster? =null
private var mHelper: DaoMaster.DevOpenHelper? =null
private var mDaoSession: DaoSession? =null
fun setDatabase() {
// 通过 DaoMaster 的内部类 DevOpenHelper,你可以得到一个便利的 SQLiteOpenHelper 对象。
// 可能你已经注意到了,你并不需要去编写「CREATE TABLE」这样的 SQL 语句,因为 greenDAO已经帮你做了。
// 注意:默认的 DaoMaster.DevOpenHelper 会在数据库升级时,删除所有的表,意味着这将导致数据的丢失。
// 所以,在正式的项目中,你还应该做一层封装,来实现数据库的安全升级。
mHelper = DaoMaster.DevOpenHelper(this, "notes-db", null)
db =mHelper!!.writableDatabase
// 注意:该数据库连接属于 DaoMaster,所以多个 Session 指的是相同的数据库连接。
mDaoMaster = DaoMaster(db)
mDaoSession =mDaoMaster!!.newSession()
}
fun getDaoSession(): DaoSession? {
return mDaoSession
}
fun getDb() : SQLiteDatabase {
return db!!
}
}
// build
applyplugin:'com.android.application'
applyplugin:'kotlin-android'
applyplugin:'org.greenrobot.greendao' // apply plugin
android {
compileSdkVersion27
buildToolsVersion'26.0.2'
defaultConfig {
applicationId "应用id"
minSdkVersion19
targetSdkVersion27
versionCode 1
versionName "1.0"
multiDexEnabled =true
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
ndk{
// 设置支持的SO库架构
abiFilters'armeabi' //, 'x86', 'armeabi-v7a', 'x86_64', 'arm64-v8a'
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'),'proguard-rules.pro'
}
}
greendao{
schemaVersion1 // 指定数据库schema版本号,迁移等操作会用到;
daoPackage'包名.greendao' // dao的包名,包名默认是entity所在的包;
targetGenDir'src/main/java' // 生成数据库文件的目录;
}
}
dependencies {
implementation fileTree(dir:'libs',include: ['*.jar'])
implementation'com.android.support:appcompat-v7:27.1.1'
implementation'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation'junit:junit:4.12'
androidTestImplementation'com.android.support.test:runner:1.0.2'
androidTestImplementation'com.android.support.test.espresso:espresso-core:3.0.2'
// // 日志上报
// implementation 'com.tencent.bugly:crashreport:2.6.6.1' //其中latest.release指代最新Bugly SDK版本号,也可以指定明确的版本号,例如2.2.0
// implementation 'com.tencent.bugly:nativecrashreport:3.3.1' //其中latest.release指代最新Bugly NDK版本号,也可以指定明确的版本号,例如3.0
// 日志上报和热更新
compile"com.android.support:multidex:1.0.3" // 多dex配置
//注释掉原有bugly的仓库
//compile 'com.tencent.bugly:crashreport:latest.release'//其中latest.release指代最新版本号,也可以指定明确的版本号,例如1.3.4
compile'com.tencent.bugly:crashreport_upgrade:1.3.5'
implementation'com.tencent.tinker:tinker-android-lib:1.9.6'
implementation'com.tencent.bugly:nativecrashreport:3.3.1' //其中latest.release指代最新Bugly NDK版本号,也可以指定明确的版本号,例如3.0
implementation'org.greenrobot:greendao:3.2.2'
compile"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" // greendao
}
repositories {
mavenCentral()
}