The framework of operating databases on Android -- greenDAO Learning
GreenDAO usage
Introduction
The official website provides the following information:
GreenDAO is an object relational ing (ORM) framework that provides an interface to operate on relational databases through object operations. It makes operations on databases easier and more convenient.
When using greenDAO, you need to create two projects, one of which is a java project, which is used to generate code domains specific to your project (that is, to generate the bean object and the dao for operating the database)
Core classes
DaoMaster:
DaoMaster saves database objects and manages DAO class classes. It provides some static methods to create and Delete tables. The internal classes OpenHelper and DevOpenHelper implement SQLiteOpenHelper and create a database framework.
DaoSession:
You can use the getter method to manage all available DAO objects. DaoSession also provides some general persistence methods, such as inserting, loading, updating, refreshing, and deleting objects.
DAOs:
Data Access Object. Each object class has a corresponding greenDAO object.
Entities:
Object Class Object
Core greenDAO class initialization Database
helper = new DaoMaster.DevOpenHelper(this, "notes-db", null);db = helper.getWritableDatabase();daoMaster = new DaoMaster(db);daoSession = daoMaster.newSession();noteDao = daoSession.getNoteDao();
The main advantage of greenDAO is that its performance is much higher than ORMLite of the same type. The test results show that greenDAO on the official website supports direct storage of protocol buffer (protobuf) protocol data. If you use protobuf to interact with the server, no ing is required. Unlike ORMLite and other ORM frameworks that use annotation, greenDAO uses the "Code generation" method, which is also the reason for its performance to be significantly improved. Method 1. Create an Android project and create a folder named java-gen In the main directory (store automatically generated beans and dao). 2. configure it in build. gradle.
// Configure sourceSets {main {java. srcDirs = ['src/main/Java', 'src/main/java-gen ']} // configure compile 'de in dependencies. greenrobot: greendao: 2.1.0'
3. Create a java project -- greenDAO_java
Add in build. gradle
compile 'de.greenrobot:greendao-generator:2.1.0'
Create a schema object and add an object (table)
Public class Generator {public static void main (String [] args) throws Exception {int version = 1; String defaultPackage = "test. greenDAO. bean "; // create mode object. Specify the version number and the package name Schema = new schema (version, defaultPackage) of the automatically generated bean object ); // specify the package name of the automatically generated dao object. If not specified, the DAO class is generated in "test. greenDAO. bean "package schema. setdefajavjavapackagedao ("test. greenDAO. dao "); // Add the entity addEntity (schema); String outDir =" D: /adt-bundle-windows-x64/workspace/studio/frame/study_demo/testgreendao/src/main/java-gen "; // call DaoGenerator (). the generateAll method automatically generates code to the new DaoGenerator () in the previously created java-gen directory (). generateAll (schema, outDir);} private static void addEntity (Schema schema) {// Add an Entity, the Entity entity Entity = schema is automatically generated. addEntity ("Entity"); // specifies the table name. If not specified, the table name is Entity (entity class name) Entity. setTableName ("student"); // Add an attribute to the object class (that is, add a field to the test table) entity. addIdProperty (). autoincrement (); // Add Id, auto-increment entity. addStringProperty ("name "). notNull (); // Add a name of the String type. The entity cannot be empty. addIntProperty ("age"); // Add the age entity of the Int type. addDoubleProperty ("score"); // Add a Double score }}
4. Run the java code to automatically generate bean and DAO classes under the java-gen directory of the Android project.
5. Create a New MyApplication to inherit the Application and configure it in the Manifest file.
Public class MyApplication extends Application {public DaoSession daoSession; public SQLiteDatabase db; public DaoMaster. devOpenHelper helper; public DaoMaster daoMaster; @ Override public void onCreate () {super. onCreate (); setupDatabase ();} private void setupDatabase () {// create a database // note: the default DaoMaster. devOpenHelper will delete all tables during Database Upgrade, which means this will cause data loss. // Therefore, in a formal project, you should also perform a layer of encapsulation to achieve database security upgrades. Helper = new DaoMaster. devOpenHelper (this, "test", null); // obtain the database connection object db = helper. getWritableDatabase (); // obtain the Database Manager daoMaster = new DaoMaster (db); // obtain the daoSession, which can be used to add, delete, modify, and query daoSession = daoMaster. newSession () ;}public DaoSession getDaoSession () {return daoSession;} public SQLiteDatabase getDb () {return db ;}}
6. Compile the MainActivity code to perform database operations using greenDAO.
Layout File
Initialize View
tv_id = (TextView)findViewById(R.id.tv_id);et_name = (EditText) findViewById(R.id.et_name);et_age = (EditText) findViewById(R.id.et_age);et_score = (EditText) findViewById(R.id.et_score);btn_add = (Button) findViewById(R.id.btn_add);btn_delete = (Button) findViewById(R.id.btn_delete);btn_update = (Button) findViewById(R.id.btn_update);btn_query = (Button) findViewById(R.id.btn_query);lv_list = (ListView) findViewById(R.id.lv_list);
Obtain the cursor object.
String orderBy = EntityDao. properties. id. columnName + "DESC"; // sort by Id in descending order // query to obtain cursorcursor = getDb (). query (getEntityDao (). getTablename (), getEntityDao (). getAllColumns (), null, orderBy );
Set listeners
btn_add.setOnClickListener(this);btn_delete.setOnClickListener(this);btn_update.setOnClickListener(this);btn_query.setOnClickListener(this);adapter = new MyAdapter(this, cursor);lv_list.setAdapter(adapter);lv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView
parent, View view, int position, long id_index) { id = cursor.getLong(0); tv_id.setText("id: "+id); et_name.setText(cursor.getString(1)); et_age.setText(cursor.getInt(2) + ""); et_score.setText(cursor.getDouble(3) + ""); }});
Custom CursorAdapter
class MyAdapter extends CursorAdapter { public MyAdapter(Context context, Cursor cursor) { super(context, cursor); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { ViewHolder holder = new ViewHolder(); LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.item_db, parent, false); holder.tv_id = (TextView) view.findViewById(R.id.tv_id); holder.tv_name = (TextView) view.findViewById(R.id.tv_name); holder.tv_age = (TextView) view.findViewById(R.id.tv_age); holder.tv_score = (TextView) view.findViewById(R.id.tv_score); view.setTag(holder); return view; } @Override public void bindView(View view, Context context, Cursor cursor) { ViewHolder holder = (ViewHolder) view.getTag(); long id = cursor.getLong(0); String name = cursor.getString(1); int age = cursor.getInt(2); double score = cursor.getDouble(3); holder.tv_id.setText(id + ""); holder.tv_name.setText(name); holder.tv_age.setText(age + ""); holder.tv_score.setText(score + ""); }}static class ViewHolder { TextView tv_id; TextView tv_name; TextView tv_age; TextView tv_score;}
Database Operations: add, delete, modify, and query methods
/*** Add */private void addEntity () {if (! TextUtils. isEmpty (name) {Entity entity = new Entity (null, name, age, score); // Add Table data to getEntityDao () for Object-Oriented purposes (). insert (entity); cursor. requery (); // refresh} else {Toast. makeText (MainActivity. this, "name cannot be blank", Toast. LENGTH_SHORT ). show () ;}}/*** Delete by id ** @ param id */private void deleteEntity (long id) {getEntityDao (). deleteByKey (id); cursor. requery ();}/*** update */private void updateList () {Entity entity = n Ew Entity (id, name, age, score); getEntityDao (). update (entity); cursor. requery ();}/*** query by name ** @ param name */private void query (String name) {if (! TextUtils. isEmpty (this. name) {// Query class represents a Query that can be repeatedly executed
Query = getEntityDao (). queryBuilder (). where (EntityDao. properties. name. eq (this. name )). orderAsc (EntityDao. properties. id ). build (); // the query result returns List count = query in List. list (); Toast. makeText (MainActivity. this, count. size () + "Data queried", Toast. LENGTH_SHORT ). show ();} else {Toast. makeText (MainActivity. this, "name cannot be blank", Toast. LENGTH_SHORT ). show ();}}
Demo: