//首先是依赖
apply plugin: 'com.android.application'
////GreenDao的配置
apply plugin: 'org.greenrobot.greendao'
android {
compileSdkVersion 26
buildToolsVersion "26.0.1"
defaultConfig {
applicationId "com.example.myapplication"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
//GreenDao的个性配置
greendao {
schemaVersion 1 //数据库版本
daoPackage 'com.sn.greendaoycf.dao' //自动生成工具类的包名
targetGenDir 'src/main/java' //路径
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
//GreenDao的配置
compile 'org.greenrobot:greendao:3.2.2'
}
//整个项目中的build.gradle文件中进行设置
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.0'
//GreenDao的配置
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()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
//User
package com.example.myapplication.bean;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;
/** * Created by 123 on 2018/1/6. */
public class User {
@Id
private Long id;
// @NotNull
private String text;
private String comment;
private java.util.Date date;
@Generated(hash = 207472317)
public User(Long id, String text, String comment, java.util.Date date) {
this.id = id;
this.text = text;
this.comment = comment;
this.date = date;
}
@Generated(hash = 586692638)
public User() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getText() {
return this.text;
}
public void setText(String text) {
this.text = text;
}
public String getComment() {
return this.comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public java.util.Date getDate() {
return this.date;
}
public void setDate(java.util.Date date) {
this.date = date;
}
}
//dao包 DaoMaster
package com.example.myapplication.dao;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;
import org.greenrobot.greendao.AbstractDaoMaster;
import org.greenrobot.greendao.database.StandardDatabase;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.database.DatabaseOpenHelper;
import org.greenrobot.greendao.identityscope.IdentityScopeType;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/** * Master of DAO (schema version 1): knows all DAOs. */
public class DaoMaster extends AbstractDaoMaster {
public static final int SCHEMA_VERSION = 1;
/** Creates underlying database table using DAOs. */
public static void createAllTables(Database db, boolean ifNotExists) {
UserDao.createTable(db, ifNotExists);
}
/** Drops underlying database table using DAOs. */
public static void dropAllTables(Database db, boolean ifExists) {
UserDao.dropTable(db, ifExists);
}
/** * WARNING: Drops all table on Upgrade! Use only during development. * Convenience method using a {@link DevOpenHelper}. */
public static DaoSession newDevSession(Context context, String name) {
Database db = new DevOpenHelper(context, name).getWritableDb();
DaoMaster daoMaster = new DaoMaster(db);
return daoMaster.newSession();
}
public DaoMaster(SQLiteDatabase db) {
this(new StandardDatabase(db));
}
public DaoMaster(Database db) {
super(db, SCHEMA_VERSION);
registerDaoClass(UserDao.class);
}
public DaoSession newSession() {
return new DaoSession(db, IdentityScopeType.Session, daoConfigMap);
}
public DaoSession newSession(IdentityScopeType type) {
return new DaoSession(db, type, daoConfigMap);
}
/** * Calls {@link #createAllTables(Database, boolean)} in {@link #onCreate(Database)} - */
public static abstract class OpenHelper extends DatabaseOpenHelper {
public OpenHelper(Context context, String name) {
super(context, name, SCHEMA_VERSION);
}
public OpenHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory, SCHEMA_VERSION);
}
@Override
public void onCreate(Database db) {
Log.i("greenDAO", "Creating tables for schema version " + SCHEMA_VERSION);
createAllTables(db, false);
}
}
/** WARNING: Drops all table on Upgrade! Use only during development. */
public static class DevOpenHelper extends OpenHelper {
public DevOpenHelper(Context context, String name) {
super(context, name);
}
public DevOpenHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory);
}
@Override
public void onUpgrade(Database db, int oldVersion, int newVersion) {
Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion + " by dropping all tables");
dropAllTables(db, true);
onCreate(db);
}
}
}
//DaoSession
package com.example.myapplication.dao;
import com.example.myapplication.bean.User;
import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.AbstractDaoSession;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.identityscope.IdentityScopeType;
import org.greenrobot.greendao.internal.DaoConfig;
import java.util.Map;
/** * Created by 123 on 2018/1/6. */
public class DaoSession extends AbstractDaoSession {
private final DaoConfig userDaoConfig;
private final UserDao userDao;
public DaoSession(Database db, IdentityScopeType type, Map>, DaoConfig>
daoConfigMap) {
super(db);
userDaoConfig = daoConfigMap.get(UserDao.class).clone();
userDaoConfig.initIdentityScope(type);
userDao = new UserDao(userDaoConfig, this);
registerDao(User.class, userDao);
}
public void clear() {
userDaoConfig.clearIdentityScope();
}
public UserDao getUserDao() {
return userDao;
}
}
//UserDao
package com.example.myapplication.dao;
import android.database.Cursor;
import android.database.sqlite.SQLiteStatement;
import com.example.myapplication.bean.User;
import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.Property;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.database.DatabaseStatement;
import org.greenrobot.greendao.internal.DaoConfig;
/** * Created by 123 on 2018/1/6. */
public class UserDao extends AbstractDao {
public static final String TABLENAME = "USER";
public static class Properties {
public final static Property Id = new Property(0, Long.class, "id", true, "_id");
public final static Property Text = new Property(1, String.class, "text", false, "TEXT");
public final static Property Comment = new Property(2, String.class, "comment", false, "COMMENT");
public final static Property Date = new Property(3, java.util.Date.class, "date", false, "DATE");
}
public UserDao(DaoConfig config) {
super(config);
}
public UserDao(DaoConfig config, DaoSession daoSession) {
super(config, daoSession);
}
public static void createTable(Database db, boolean ifNotExists) {
String constraint = ifNotExists? "IF NOT EXISTS ": "";
db.execSQL("CREATE TABLE " + constraint + "\"USER\" (" + //
"\"_id\" INTEGER PRIMARY KEY ," + // 0: id
"\"TEXT\" TEXT," + // 1: text
"\"COMMENT\" TEXT," + // 2: comment
"\"DATE\" INTEGER);"); // 3: date
}
public static void dropTable(Database db, boolean ifExists) {
String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"USER\"";
db.execSQL(sql);
}
@Override
public User readEntity(Cursor cursor, int offset) {
User entity = new User( //
cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // text
cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // comment
cursor.isNull(offset + 3) ? null : new java.util.Date(cursor.getLong(offset + 3)) // date
);
return entity;
}
@Override
public Long readKey(Cursor cursor, int offset) {
return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
}
@Override
public void readEntity(Cursor cursor, User entity, int offset) {
entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
entity.setText(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1));
entity.setComment(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2));
entity.setDate(cursor.isNull(offset + 3) ? null : new java.util.Date(cursor.getLong(offset + 3)));
}
@Override
protected final void bindValues(DatabaseStatement stmt, User entity) {
stmt.clearBindings();
Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
String text = entity.getText();
if (text != null) {
stmt.bindString(2, text);
}
String comment = entity.getComment();
if (comment != null) {
stmt.bindString(3, comment);
}
java.util.Date date = entity.getDate();
if (date != null) {
stmt.bindLong(4, date.getTime());
}
}
@Override
protected final void bindValues(SQLiteStatement stmt, User entity) {
stmt.clearBindings();
Long id = entity.getId();
if (id != null) {
stmt.bindLong(1, id);
}
String text = entity.getText();
if (text != null) {
stmt.bindString(2, text);
}
String comment = entity.getComment();
if (comment != null) {
stmt.bindString(3, comment);
}
java.util.Date date = entity.getDate();
if (date != null) {
stmt.bindLong(4, date.getTime());
}
}
@Override
protected final Long updateKeyAfterInsert(User entity, long rowId) {
entity.setId(rowId);
return rowId;
}
@Override
public Long getKey(User entity) {
if(entity != null) {
return entity.getId();
} else {
return null;
}
}
@Override
public boolean hasKey(User entity) {
return entity.getId() != null;
}
@Override
protected final boolean isEntityUpdateable() {
return true;
}
}
//MainActivity
package com.example.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.myapplication.bean.User;
import com.example.myapplication.dao.DaoSession;
import com.example.myapplication.dao.UserDao;
import org.greenrobot.greendao.query.Query;
import java.util.Date;
import java.util.List;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private UserDao userDao;
private AutoCompleteTextView text;
private AutoCompleteTextView comment;
private Button butAddData;
private Button butShowData;
private Button butDelData;
private Button butModifyData;
private TextView tShow;
private EditText num;
private Query userQuery;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DaoSession daoSession = ((MyApplication) getApplication()).getDaoSession();
userDao = daoSession.getUserDao();
initView();
}
private void initView() {
text = (AutoCompleteTextView) findViewById(R.id.edit_text);
comment = (AutoCompleteTextView) findViewById(R.id.edit_comment);
tShow = (TextView) findViewById(R.id.text_show_data);
num = (EditText) findViewById(R.id.exit_id);
butAddData = (Button) findViewById(R.id.but_add_data);
butShowData = (Button) findViewById(R.id.but_show_data);
butDelData = (Button) findViewById(R.id.but_del_data);
butModifyData = (Button) findViewById(R.id.but_modify_data);
butAddData.setOnClickListener(this);
butShowData.setOnClickListener(this);
butDelData.setOnClickListener(this);
butModifyData.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.but_add_data://增
String test = text.getText().toString();
String con = comment.getText().toString();
User user = new User();
user.setComment(con);
user.setDate(new Date());
user.setText(test);
userDao.insert(user);
text.setText("");
comment.setText("");
break;
case R.id.but_show_data://查询
//按找id z-a排序查询
// userQuery = userDao.queryBuilder().orderDesc(UserDao.Properties.Id).build();
//按找id a-a排序查询
userQuery = userDao.queryBuilder().orderAsc(UserDao.Properties.Id).build();
//查询满足指定属性值的结果
//userQuery = userDao.queryBuilder().where(UserDao.Properties.Text.eq(33),UserDao.Properties.Comment.eq(22)).build();
List datalist= userQuery.list();
StringBuffer res = new StringBuffer();
for (User user1 : datalist) {
res.append("id= "+user1.getId());
res.append(" text="+user1.getText());
res.append(" comment="+user1.getComment()+"\n");
//res.append(" date="+user1.getDate()+"\n");
}
tShow.setText(res.toString());
break;
case R.id.but_del_data://删除
String index = num.getText().toString().trim();
if(TextUtils.isEmpty(index)){
Toast.makeText(MainActivity.this, "不能输入为空", Toast.LENGTH_SHORT).show();
return;
}
userDao.deleteByKey(Long.valueOf(index));
num.setText("");
break;
case R.id.but_modify_data://修改
String www = num.getText().toString().trim();
if(TextUtils.isEmpty(www)){
Toast.makeText(MainActivity.this, "不能输入为空", Toast.LENGTH_SHORT).show();
return;
}
String test2 = text.getText().toString();
String con2 = comment.getText().toString();
User user2 = new User();
user2.setId(Long.valueOf(www));
user2.setComment(con2);
user2.setDate(new Date());
user2.setText(test2);
userDao.update(user2);
text.setText("");
comment.setText("");
num.setText("");
break;
}
}
}
//MyApplication
package com.example.myapplication;
import android.app.Application;
import com.example.myapplication.dao.DaoMaster;
import com.example.myapplication.dao.DaoSession;
import org.greenrobot.greendao.database.Database;
/** * Created by 123 on 2018/1/6. */
public class MyApplication extends Application{
public static final boolean ENCRYPTED = true;
private DaoSession daoSession;
@Override
public void onCreate() {
super.onCreate();
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, ENCRYPTED ? "notes-db-encrypted" : "notes-db");
Database db = !ENCRYPTED ? helper.getEncryptedWritableDb("super-secret") : helper.getWritableDb();
daoSession = new DaoMaster(db).newSession();
}
public DaoSession getDaoSession() {
return daoSession;
}
}
//xml
<LinearLayout android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.myapplication.MainActivity">
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal">
<AutoCompleteTextView android:id="@+id/edit_comment" android:layout_width="0dp" android:hint="comment" android:layout_height="wrap_content" android:layout_weight="1" android:padding="5dp" />
<AutoCompleteTextView android:id="@+id/edit_text" android:layout_width="0dp" android:layout_height="wrap_content" android:hint="text" android:layout_weight="1" android:padding="5dp" />
LinearLayout>
<Button android:id="@+id/but_add_data" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="添加数据" android:padding="5dp" />
<ImageView android:layout_width="match_parent" android:layout_height="3dp" android:background="#ff0"/>
<Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="显示数据" android:id="@+id/but_show_data"/>
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/text_show_data" android:layout_gravity="center" android:gravity="center" android:hint="这里将显示数据库中的数据"/>
<Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/but_del_data" android:text="删除"/>
<EditText android:layout_width="match_parent" android:layout_height="40dp" android:hint="输入要删除或者要修改的id值" android:id="@+id/exit_id" android:inputType="number" />
<Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/but_modify_data" android:text="修改"/>
LinearLayout>
最后.name