How to Make Android Database Operations generic (3)

Source: Internet
Author: User

How to Make Android Database Operations generic (3)

Overview leisurely green water standing by the Forest invasion sunset watching the mountains four look back to the Youlin ancient temple Gu Mingyue cold well Cold Spring Bi ou flying manpu fishing boat Pan crane with idle pavilion xianke come travel path walking flowers smoke go Liuxi far a tent open

Overview

I wrote three articles accidentally, but I don't know if you can understand them? If you don't understand it, you 'd better leave a message for me. I 'd better correct it next time.

Next, the preparations have been completed last time. Now we are about to solve the five problems of blocking the generalization of Android database operations.

Let's first review the question: Question 1: Table Name acquisition Question 2: How to import data in an object to a database based on the corresponding relationship question 3: Who is the primary key in an object? Problem 4: How to encapsulate the data of columns in a database table according to the corresponding relationship. Problem 5: The object creation of the object is a long time, watching the mountains at sunset.

The problem is solved one by one so as to be efficient. The first problem comes:How to obtain the table name.

Generally, a method or function is used to solve a problem. This is no exception. Let's first give a shell:

/** Question 1: Table Name acquisition **/public String getTableName () {return null ;}

Everything is full of hope and natural. Now we have to start thinking about how to get the table name.

In actual development, each database table corresponds to a specific entity. It's likenewsThe table correspondsNewsClass. Look at them. are their names similar? Only one is an upper-case letter, and the other is a lower-case letter. So we thought,If we can get the table name through "entity ",.

Now that you have a path to go, you can see that the path is still disconnected.

We can propose two solutions: ① if we can get the entity, we can get the simple name of the object, and then we only need to write the first letter in lowercase as the table name. However, this disadvantage is also obvious, which requires that the names of the database-defined tables be basically the same as those of the Entities, which will lead to restrictions on the names of the defined entities. For example newsTable, the corresponding entity can only be News. ② Using annotations, the relationship between the object name and the name of the database table can be separated, and the two do not interfere with each other. The disadvantage is also obvious. The encoding difficulty increases (hey). But if we are experienced developers, this is the case.

If some comments have been forgotten or are not clear, read this article: www.bkjia.com.

Gu Mingyue, Yulin ancient temple, Leng Jing Cold Spring Bi Tai.

If the road is clear, you can move forward.

Next we need to use annotations and reflections !! Is it a little excited ~ Haha ~

The next task isTo NewsThe object class adds an annotation. The purpose of adding the annotation is to determine the relationship between the database table and the corresponding object. See the Code:

// Annotation: determines the database table and corresponding entity. @ TableName (DBHelper. TABLE_NEWS_NAME) public class News {private int id; private String title; private String summary ;}

Looks decent,@TableName(DBHelper.TABLE_NEWS_NAME)What is this sentence? Who can tell me?

This is the annotation we wrote. However, we haven't created it yet, but it doesn't matter. If you are using Eclipse, please select this line.Ctrl+1, You can automatically create it. Was it shocked when it was so tall! (^ ω ^ ). Please refer to the specificTableNameCode:

/*** Specifies the ing between objects and tables in the database */@ Target (ElementType. TYPE) // specify the position to be placed @ Retention (RetentionPolicy. RUNTIME) // specify the survival time public @ interface TableName {/*** table name in the database. The value */String value () can be stored here ();}

Everything is so simple and easy to understand. Now the annotation has been created, the Annotation on the object has been added, and the table name has been passed in. NextgetTableNameMethod, just enter the code again.

The table name is still obtained in two steps: ① obtain the object-this is Question 5 ② obtain the Annotation on the object header, and determine the table to be operated based on the value Setting value.

The first step in pseudo-code is to obtain the object entity. After viewing it, this is exactly the fifth problem. Let's put it first and write an empty method to represent it.

/*** Question 5: Object object creation */private M getInstance () {return null ;}

SpecificgetTableName()The method code is as follows:

Public String getTableName () {// pseudocode: // ① question 5: Obtain the object's object M = getInstance (); // ② obtain the Annotation on the object header, based on the value Setting value, determine the database table for the Operation // note that you want to get the annotation information during the "RunTime" and set the survival time for the annotation. TableName tableName = m. getClass (). getAnnotation (TableName. class); // annotationType annotation type // determine the validity of the annotation for security reasons; if (tableName! = Null) {return tableName. value ();} return null ;}

With this method,BaseDaoSupportIndeleteThe method can also be written, which is still very simple. Please refer to the Code:

@Overridepublic int delete(Serializable id) {    return db.delete(getTableName(), DBHelper.TABLE_ID + =?, new String[] { id.toString() });}

Summary:In fact, in table name acquisition, we use annotations to solve a problem. Tables and entities correspond one by one and what are the mappings between them. (TableName)

Yunfei manpu fishing boat, crane with xianlaike.

It's time to show the real technology !! (Operator _ operator )#

Next we should solve the second problem,How to import data in an object to a database according to the corresponding relationship.

Looking back at the solution to the first problem, we actually used annotations to solve the ing between tables and entities. Similarly, the second problem also requires that the data in the entity be imported into the database according to the corresponding relationship. In the same way, we can continue to provide an annotation for the object fields to reflect the correspondence with the columns in the database table. See the Code:

/*** Specifies the correspondence between the sub-Bank of the object and the columns in the database table */@ Target (ElementType. FIELD) // specify the position to be placed @ Retention (RetentionPolicy. RUNTIME) // specify the survival time public @ interface Column {String value ();}

As long as the field has this annotation, it must be related to the columns in the database table. Next, add the corresponding annotation for the field of the object and input the column name. See the Code:

// Annotation: determines the database table and corresponding entity. @ TableName (DBHelper. TABLE_NEWS_NAME) public class News {// specifies the ing between objects and tables in the Database @ Column (DBHelper. TABLE_ID) private int id; @ Column (DBHelper. TABLE_NEWS_TITLE) private String title; @ Column (DBHelper. TABLE_NEWS_SUMMARY) private String summary ;}

The preparation is complete.insertThe code in. A newfillColumn(M m, ContentValues values)Method, put the object M field value and FieldColumn(XXX)Name of the column passed in the annotationvalues.put(key,value)Enter the method in valeus so thatinsert. The Code is as follows:

@ Overridepublic long insert (M m) {ContentValues values = new ContentValues (); // m indicates the data source. vlaues is the target fillColumn (m, values) for data import; return db. insert (getTableName (), null, values );}

The code is very simple. The key lies infillColumn(m, values);. The reflection technology is used to obtainMAll fields of the instance, and then get the values of each field and the values of each field annotation in turn, and fill invaluesSee the Code:

/*** Question 2: How to import data in an object, * @ param m data source * @ param values is the data import destination */public void fillColumn (M m, ContentValues values) {// obtain all fields Field [] fields = m. getClass (). getDeclaredFields (); for (Field field: fields) {// set the access permission field. setAccessible (true); // obtain the annotation Column column = field. getAnnotation (Column. class); if (column! = Null) {try {String key = column. value (); // obtain the String value = field in the annotation. get (m ). toString (); // obtain the field value // enter the data values. put (key, value);} catch (IllegalArgumentException e) {throw new RuntimeException (the field does not belong to the m instance);} catch (IllegalAccessException e) {throw new RuntimeException (You are not authorized to access the field domain );}}}}

Summary:As long as you have mastered the ideas and methods, clean and clear code, it is not that difficult to write.

Walking on the walking path and walking on the smoke, Liuxi is far away.

Life does not meet each other, such as participating in the business.
The light is candlelight.
When can the young man be, the old man and the old man.
The old half is a ghost, and the hot MIIT is exclaimed.
Yanzhi has been carrying on 20 years and is now in junzitang.
XI binjun was unmarried, and his children suddenly went on line ......

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.