How to Make Android Database Operations generic (1)

Source: Internet
Author: User
Tags web database

How to Make Android Database Operations generic (1)

Summary little note after a farewell second place hanging are said to be three in April who knows year 56 seven strings piano unintentional play eight lines of books can not be passed nine links from the broken ten long Pavilion in a bid

Overview

StartBefore considering Android database operations, let's look back at the Web database operations. If we just stay in the simple use and encapsulation of JDBC (such as pure JDCB or DBUtils), even if weAdd, delete, modify, and queryThe operation extracts the interface, and the code will stillBusinessStrong coupling.

AfterIn our analysis, the key to decoupling is how to automatically map the ing between "entity classes and database tables. If we can achieve this step, we can better decouple and reduce the code repetition rate.

IfWe can use a better framework (such as Hibernate) across the previous step, which will become simple and convenient. Hibernate provides us with two ways to establish the relationship between "entity classes (beans)-database tables.

One typeThe configuration file is used to configure the relationships among table names, fields, and entities in the configuration file. Hibernate can do everything for us. The following is a configuration file example:


  
   
    
     
      
       
        
         
          
            
           
           
         
        
       
      
     
    
   
  

Another, Is to useAnnotation. Hibernate provides us@Entity,@Table,@Id,@Column,@GeneratedValueAnd many other annotations. We only need to add these annotations in the appropriate places to configure the relationship for our classes and fields, and Hibernate can do everything for us. Below is a configuration file example:

@ Entity (name = brand)/* Entity bean */@ Table (name = brand_t) /* specify the name of the table to be generated */public class Brand implements Serializable {/** @ Fields code: ID: Use UUID to generate **/private String code;/** @ Fields name: brand name **/private String name;/** @ Fields visible: visible? **/private Boolean visible = true;/** @ Fields logopath: logo path **/private String logopath; public Brand (String name, String logopath) {this. name = name; this. logopath = logopath;} @ Id @ Column (name = code, length = 36)/* UUID is 36 */@ GeneratedValue (generator = system-uuid) @ GenericGenerator (name = system-uuid, strategy = uuid) public String getCode () {return code;} public void setCode (String code) {this. code = code ;}@ Column (length = 40, nullable = false) public String getName () {return name ;}@ Column (nullable = false) public Boolean getVisible () {return visible;}/*/images/brand/2012/12/8/9/sss.gif */@ Column (length = 80, nullable = true) public String getLogopath () {return logopath ;}}

Out of wordsBack to the Android we love, how should we write a general database addition, deletion, modification, and query operation on Android? We may also need to learn from the excellent ideas of Hibernate.

HoweverEverything in the world is evolved step by step. Our code is also like this. It never applies to general purposes. I will show you through several blogs one by one. However, due to my limited experience and knowledge, you cannot build a complete open-source project. If you are interested, please contact us for a try (every time you sigh, If you have such a thing, please note that this is your chance ).

Notes

The whole example uses a news entity as the basic element and runs through the whole example. The news entity is very simple. Let's name itNews, The field is composedid,title,summary. The following is the sample code:

Public class News {private int id; private String title; private String summary; // The get and set methods are omitted here}

In addition, the vast majority of stored items in the SQLite database are of the String type. int is used only when primary key and auto-increment are involved.

Finally, it is too painful to find some interesting poems on the Internet as chapter names.

The second place is suspended.

We already have entity objects, so the database table is now worse. Now let's look back at the operation steps of database tables in Android, inherit from SQLiteOpenHelper, modify some constructors, and then use the database in onCreate to execute the table creation statement, it seems that the database version is complete (I will talk about it later ). See the sample code:

Public class DBHelper extends SQLiteOpenHelper {private static final int VERSION = 1; private static final String NAME = bzh. db; public DBHelper (Context context) {super (context, NAME, null, VERSION);} // news table: Primary Key + title + Abstract public static final String TABLE_ID = _ id; public static final String TABLE_NEWS_NAME = news; public static final String TABLE_NEWS_TITLE = title; public static final String TABLE_NEWS_SUMMARY = summary; @ Override public void onCreate (SQLiteDatabase db) {db.exe cSQL (create table + TABLE_NEWS_NAME + (+ // TABLE_ID + integer primary key autoincrement, + // TABLE_NEWS_TITLE + varchar (50), + // TABLE_NEWS_SUMMARY + varhcar (200 )) //) ;}@ Override public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion ){}}

Take a closer look at the code. We have extracted all fields and table names into constant fields, which makes it easier for us to use when writing database add, delete, modify, and query operations.

All said it was April, and who knows year 56.

Now, the entity and table are available. It is time to add, delete, modify, and query operations. Since it is an addition, deletion, modification, and query, there must be a correspondinginsert,delete,update,findAllAnd so on.
As an experienced developer (sneer), we must first writeNewsDaoAs a whole, it is very simple, so I will not write comments. The Code is as follows:

public interface NewsDao {    long insert(News news);    int delete(int id);    int update(News news);    List
  
    findAll();}
  

It seems that everything is going smoothly. The following is the time to write the Dao implementation class, which is calledNewsDaoImplAnd implementNewsDaoInterface. The Code is as follows:

public class NewsDaoImpl implements NewsDao {    private Context context;    private DBHelper helper;    private SQLiteDatabase db;    public NewsDaoImpl(Context context) {        super();        this.context = context;        this.helper = new DBHelper(context);        this.db = helper.getWritableDatabase();    }    @Override    public long insert(News news) {        return 0;    }    @Override    public int delete(int id) {        return 0;    }    @Override    public int update(News news) {        return 0;    }    @Override    public List
  
    findAll() {        return null;    }}
  

It looks like this. To execute the add, delete, modify, query, and other statements, we need a previously written DBHelper instance, and DBHelper requires that the Context object be passed in. Then DBHelper gave us another instance for operating the database SQLiteDatabase.

Everything went well, but the addition, deletion, modification, and query methods were empty. It seems that you only need to fill in the blanks.

The seven-character piano is unintentional, and the eight lines of books cannot be passed in.

Since we are filling in the blanks, we can only come one by one, which is too troublesome (no wonder programmers like to be lazy, meow !).

Start frominsertLet's get started.

@ Overridepublic long insert (News news) {ContentValues values = new ContentValues (); values. put (DBHelper. TABLE_NEWS_TITLE, news. getTitle ());//... N lines of code return db are omitted here. insert (DBHelper. TABLE_NEWS_NAME, null, values );}

Of course, I am just an exemplary code. You may have omitted a lot.insertIs not complicated at all. First, store the correspondence between field names and object fields one by one.ContentValuesAnd then executedb.insertAnd enter the name and data of the table to be inserted. After you search for the table, the operation is successful.

NextdeleteIt seems easier. IndeleteThe table name, filter condition, and parameters corresponding to the filter condition are OK.

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

Below isupdateMethod. Prepare the data for the update.updateEnter the corresponding table name, update value, filter condition, and parameters corresponding to the filter condition. Of course, the code is omitted for laziness. I promise that the next statement will be complete.

@ Overridepublic int update (News news) {ContentValues values = new ContentValues (); values. put (DBHelper. TABLE_NEWS_TITLE, news. getTitle ());//... N lines of code return db are omitted here. update (DBHelper. TABLE_NEWS_NAME, values, DBHelper. TABLE_ID + = ?, New String [] {news. getId () + });}

TurnfindAllThis method is more important. Please listen carefully. We passdb.query()Query the data and obtain the cursor (do not forget to close it). Then, move the cursor, extract the data, and encapsulate the dataNewsEntity, and then addList. Okay, I admit, it's just a bit lazy here, hey.

@ Overridepublic List
  
   
FindAll () {List
   
    
Result = null; // List
    
     
Cursor cursor = db. query (DBHelper. TABLE_NEWS_NAME, null); if (cursor! = Null) {result = new ArrayList
     
      
(); While (cursor. moveToNext () {News news = new News (); // M m = new M (); int columnIndex = cursor. getColumnIndex (DBHelper. TABLE_NEWS_NAME); String title = cursor. getString (columnIndex); news. setTitle (title );//... N lines of code result are omitted here. add (news) ;}// close the cursor. close (); return result ;}
     
    
   
  

Step by step.NewsObject addition, deletion, modification, and queryDaoBut as a programmer, writing like this can still be tolerated, so in case there are moreUser,AAA,BBB,CCCWait, what should I do?

Do I have to write a lot of data?UserDao,UserDaoImpl,AAADao,AAADaoImplAnd so on? God, you should have killed me.

Then, the problem arises. What problems do the above Code need to solve before it becomes universal?

The nine links are broken from them!

Next we start frominsert,delete,update,findAllThese methods are analyzed in sequence to find out which problems are blocking our general steps.

insertMedium,

ContentValues values = new ContentValues (); values. put (DBHelper. TABLE_NEWS_TITLE, news. getTitle (); //... N lines of code are omitted here

If the code can be "automatic", even if our hands are freed up, we need to face the following problems:How to import data in an object to a corresponding table according to the corresponding relationship.

return db.insert(DBHelper.TABLE_NEWS_NAME, null, values);

Let's look at this sentence, as if in Java, writing dead is equal to coupling, which is inconvenient. WhileDBHelper.TABLE_NEWS_NAMEIt seems that it is also fixed in the statement. It seems that this Code also blocks the pace for us to free our hands. We need to face the following problems:How to obtain the table name.

This method is gone. Let's take a look.delete,

return db.delete(DBHelper.TABLE_NEWS_NAME, DBHelper.TABLE_ID + =?, new String[] { id +  });

TheDBHelper.TABLE_NEWS_NAMEWe have recorded it.DBHelper.TABLE_IDWhy? Oh, it turns out to be a primary key, but it is also fixed to the dead. It seems that this is also a problem we are facing:Identify the primary key in the object and obtain the value encapsulated in the primary key.

Let's take a look.updateMethod ~ No! Then proceed to the nextfindAllMethod.

News news = new News (); // M m = new M (); int columnIndex = cursor. getColumnIndex (DBHelper. TABLE_NEWS_NAME); String title = cursor. getString (columnIndex); news. setTitle (title );//... N lines of code www.bkjia.com are omitted here

Here, we extract the data from the cursor and place it in the corresponding object attribute. Here, errors are most likely to occur and they are also written to death. It seems that this is also one of the problems:Import the column data in the database table to the object according to the corresponding relationship.

After the analysis, we can summarize the articles, articles, articles. Haha. (It seems that there are not so many .)

What problems do we need to solve in order to become universal? ① Obtain the table name ② how to import data in the object to the corresponding table according to the corresponding relationship. ③ Identify the primary key in the object and obtain the value encapsulated in the primary key. ④ Create an object ⑤ import the data in the columns in the database table to the object according to the corresponding relationship.

The above are all the problems. If we can solve these problems, general database operations in Android will emerge.

What is time? It can change everything, take everything away, and leave everything. Yesterday seems to be in front of us, but today is quietly past, our life is always so limited, and the young people who belong to you and me are so arrogant that they are unaware of their possession. When the past is past, it has become a thing of an eye, only then can I understand that I have spent the good time, and the years are still there, but I forget to silently make that humble wish in my heart.

Related Article

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.