Android Development--ormlite

Source: Internet
Author: User

Ormlite is a hibernate-like object-mapping framework, primarily for the Java language, and is the most popular Android-database-oriented programming tool nowadays.
Official website: http://ormlite.com/
If you need to develop Android, you only need to download the core and Android two jar packages:

    

  

 Use of Ormlite

1, establishing a mapping relationship

The mapping between Ormlite and the database is illustrated by annotations.
Comments are divided into tables and for individual columns: @DatabaseTable, comment tables, @DatabaseField comments for individual columns.

· First Note: table,@

databasetable If you default to the class name, you do not need to add a class name comment.

· Then: Identify the fields you want, and add comments to the fields: @DatabaseField If you have specific requirements for a field, add the following related comments, such as ID.

    

@DatabaseTable (tablename= "T_message") Public classMessage {@DatabaseField (Generatedid=true)    Private intID; @DatabaseField (ColumnName= "TOU1")    PrivateString tou1; @DatabaseField (ColumnName= "UserName")    PrivateString UserName; @DatabaseField (ColumnName= "Lastmessage")    PrivateString Lastmessage; @DatabaseField (ColumnName= "DateTime")    PrivateString datetime;  PublicString getTou1 () {returntou1; }     Public voidsetTou1 (String tou1) { This. TOU1 =tou1; }

    2, database creation and basic tools

In the development of Android, the original Google packaged a sqliteopenhelper for developers to call, in Ormlite, the original tool has been enhanced, Provides a ormlitesqliteopenhelper tool that inherits from Sqliteopenhelper.

Like Android, we inherit this tool class. 

 Public classDatabasehelperextendsOrmlitesqliteopenhelper {Private Static FinalString db_name = "mydata.db";//Database name    Private Static Final intVersion = 2;//Database Version//define member variables for each table, one of the functions: Close helper, all DAO object cleanup    PrivateDao<message, integer>Messagedao;  PublicDao<message, integer>Getmessagedao () {if(messagedao==NULL){            Try{Messagedao= Getdao (Message.class); } Catch(SQLException e) {e.printstacktrace (); }        }        returnMessagedao; }     PublicDatabasehelper (Context context) {Super(Context, Db_name,NULL, version); }    /** 1. This method does not customize execution because it is not a callback function * 2. It is best not to call it yourself, because it should only be performed 1 times*/@Override Public voidonCreate (sqlitedatabase arg0, Connectionsource arg1) {//TODO auto-generated Method Stub            }    /** This method is not self-executing because it is not a callback function*/@Override Public voidOnupgrade (sqlitedatabase arg0, Connectionsource arg1,intArg2,intArg3) {        //TODO auto-generated Method Stub            }

Mydatabaseopenhelper class

  

 Public classMydatabaseopenhelperextendsSqliteopenhelper {Private Static FinalString db_name = "mydata.db";//Database name    Private Static Final intVersion = 2;//Database Version     PublicMydatabaseopenhelper (Context context) {Super(Context, Db_name,NULL, version); }@Override Public voidonCreate (Sqlitedatabase db) {//TODO auto-generated Method Stub//write a "start from 0 to latest State" build Table statementLOG.I ("Hi", "no database, create DATABASE, create v2.0 success"); String Sql_message= "CREATE table t_message (ID int primary KEY,TOU1 varchar (), userName varchar (), lastmessage varchar (), datetime var CHAR (50)) "; String sql_init_1= "INSERT into t_message values (1, ' abc ', ' ABC1 ', ' abcd1 ', ' hi1 ')"; String sql_init_2= "INSERT into t_message values (2, ' abc ', ' ABC2 ', ' abcd2 ', ' hi1 ')"; String Sql_init_3= "INSERT into t_message values (3, ' abc ', ' ABC2 ', ' abcd2 ', ' hi1 ')";        Db.execsql (Sql_message);        Db.execsql (sql_init_1);        Db.execsql (sql_init_2);    Db.execsql (Sql_init_3); }

Mainactivity class, ListView display Data

 Public classMainactivityextendsActivity {PrivateSimpleadapter sa; PrivateListView LV; PrivateList<message> messagelist =NewArraylist<message>(); Privatelist<map<string,object> > MessageList2 =Newarraylist<map<string,object> >(); PrivateList<message> MessageList3;//Demo for Ormlite        PrivateDatabasehelper Db_helper; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (r.layout.weixin); //This 3 line of code is used to create the table structure and initialize the dataMydatabaseopenhelper helper =NewMydatabaseopenhelper (mainactivity. This); Sqlitedatabase DB=helper.getwritabledatabase ();                    Db.close (); LV=(ListView) Findviewbyid (R.ID.LISTVIEW1); SA=NewSimpleadapter ( This, MessageList2,//Data is a data mix coupled to the interfaceR.layout.listview_item_layout,NewString[] {"Tou", "UserName", "Lastmessage", "datetime"},//from Never come                New int[] {r.id.imageview1,r.id.tv_username,r.id.tv_lastmessage,r.id.tv_datetime}//to get there.                );        Lv.setadapter (SA); Lv.setonitemclicklistener (NewOnitemclicklistener () {@Override Public voidOnitemclick (adapterview<?>Parent, view view,intPositionLongID) {MAP<String,Object> item =Messagelist2.get (position); Item.put ("UserName", "Zhao Benshan" +position);                Sa.notifydatasetchanged (); //Toast.maketext (Mainactivity.this, (String) item.get ("UserName"), Toast.length_short). Show ();                                                                    }                 }); //UI present in front of you@Overrideprotected voidOnresume () {LOG.I ("OK", "Onresume, Interface appears"); //using OrmliteDb_helper =NewDatabasehelper ( This); Dao<message, integer> Message_dao =Db_helper.getmessagedao (); Try{messageList3=Message_dao.queryforall (); //log.i ("Ormlite", "Number of record strips:" +messagelist3.size ());String T = "Number of record bars:" +messagelist3.size (); Toast.maketext ( This, T, Toast.length_long). Show (); } Catch(SQLException e) {String T= "Remember error:" +E.getmessage (); Toast.maketext ( This, T, Toast.length_long). Show (); }                     for(inti = 0; I < messagelist3.size (); i++) {                                //define a mix of interfaces and data, one item for a row of recordsmap<string,object> item =NewHashmap<string,object>(); //one row of records, containing multiple controlsItem.put ("Tou", R.DRAWABLE.TOU1); Item.put ("UserName", Messagelist3.get (i). GetUserName () +i); Item.put ("Lastmessage", Messagelist3.get (i). Getlastmessage ()); Item.put ("DateTime", Messagelist3.get (i). GetDateTime ());        Messagelist2.add (item); }        Super. Onresume (); }

    

    

Note: Ormlite also provides some base classes, such as Ormlitebaseactivity,ormlitebaseservice, to facilitate the operation of the database,

Android Development--ormlite

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.