轉載自:http://www.reibang.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();
? ? ? ? ? ? }
});
? ? }
/**
* 查詢數(shù)據(jù)庫中的所有數(shù)據(jù),并顯示到適配器上
*/
? ? 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();
? ? }
/**
* 清空數(shù)據(jù)庫
*/
? ? 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 對象。
// 可能你已經(jīng)注意到了回挽,你并不需要去編寫「CREATE TABLE」這樣的 SQL 語句没咙,因為 greenDAO已經(jīng)幫你做了。
// 注意:默認的 DaoMaster.DevOpenHelper 會在數(shù)據(jù)庫升級時千劈,刪除所有的表祭刚,意味著這將導致數(shù)據(jù)的丟失。
// 所以墙牌,在正式的項目中涡驮,你還應該做一層封裝,來實現(xiàn)數(shù)據(jù)庫的安全升級喜滨。
? ? ? ? mHelper = DaoMaster.DevOpenHelper(this, "notes-db", null)
db =mHelper!!.writableDatabase
? ? ? ? // 注意:該數(shù)據(jù)庫連接屬于 DaoMaster捉捅,所以多個 Session 指的是相同的數(shù)據(jù)庫連接。
? ? ? ? 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 // 指定數(shù)據(jù)庫schema版本號虽风,遷移等操作會用到;
? ? ? ? daoPackage'包名.greendao' // dao的包名棒口,包名默認是entity所在的包;
? ? ? ? targetGenDir'src/main/java' // 生成數(shù)據(jù)庫文件的目錄;
? ? }
}
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' //其中l(wèi)atest.release指代最新Bugly SDK版本號辜膝,也可以指定明確的版本號无牵,例如2.2.0
//? ? implementation 'com.tencent.bugly:nativecrashreport:3.3.1' //其中l(wèi)atest.release指代最新Bugly NDK版本號,也可以指定明確的版本號厂抖,例如3.0
// 日志上報和熱更新
? ? compile"com.android.support:multidex:1.0.3" // 多dex配置
//注釋掉原有bugly的倉庫
//compile 'com.tencent.bugly:crashreport:latest.release'//其中l(wèi)atest.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' //其中l(wèi)atest.release指代最新Bugly NDK版本號忱辅,也可以指定明確的版本號七蜘,例如3.0
? ? implementation'org.greenrobot:greendao:3.2.2'
? ? compile"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" // greendao
}
repositories {
mavenCentral()
}