Getting started with the Android ormlite framework

Source: Internet
Author: User

Reprint please indicate source: http://blog.csdn.net/lmj623565791/article/details/39121377

We will use the database more or less in Android projects, in order to improve our development efficiency, of course, the database ORM framework, especially some database operations especially frequent apps; This blog details the easy usage of ormlite.

Here's how to get started with Ormlite ~

1. Download Ormlite Jar

First go to ormlite official website download jar package, for Android: Ormlite-android-4.48.jar and Ormlite-core-4.48.jar;

PS: Friends can not access, the end of the article will be the jar, source code, doc and this blog example packaged together to provide for everyone to download.

2. Configure Bean Class

With the jar, we create a new project as: Zhy_ormlite, then copy the jar to Libs.

Then create a new package: Com.zhy.zhy_ormlite.bean is dedicated to storing the beans in the project, first creating a new User.java

Package Com.zhy.zhy_ormlite.bean;import Com.j256.ormlite.field.databasefield;import com.j256.ormlite.table.DatabaseTable; @DatabaseTable (tableName = "Tb_user") public class user{@DatabaseField ( Generatedid = true) private int id; @DatabaseField (columnName = "name") private String name; @DatabaseField (columnName = " Desc ") Private String Desc;public user () {}public User (string name, String desc) {this.name = NAME;THIS.DESC = desc;} public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public String GetDesc () {return desc;} public void Setdesc (String desc) {this.desc = desc;}}

First add @databasetable (tableName = "Tb_user") on the user class, indicating that this is a table in the database, marked as Tb_user

Then add @databasefield (columnName = "name") on the property, and the value of ColumnName is the column name of the field in the data

@DatabaseField (Generatedid = True), Generatedid represents the ID as the primary key and is automatically generated

3. Writing DAO class

Native database operations, need to inherit sqliteopenhelper, here we need to inherit ormlitesqliteopenhelper, look at the code:

Package Com.zhy.zhy_ormlite.db;import Java.sql.sqlexception;import Android.content.context;import Android.database.sqlite.sqlitedatabase;import Com.j256.ormlite.android.apptools.ormlitesqliteopenhelper;import Com.j256.ormlite.dao.dao;import Com.j256.ormlite.support.connectionsource;import Com.j256.ormlite.table.tableutils;import Com.zhy.zhy_ormlite.bean.user;public class DatabaseHelper extends Ormlitesqliteopenhelper{private static final String table_name = "SQLITE-TEST.DB";/** * Userdao, each table for a */private dao&lt ; User, integer> userdao;private databasehelper (context context) {Super (context, TABLE_NAME, NULL, 2);} @Overridepublic void OnCreate (sqlitedatabase database,connectionsource connectionsource) {try{ Tableutils.createtable (Connectionsource, user.class);} catch (SQLException e) {e.printstacktrace ();}} @Overridepublic void Onupgrade (sqlitedatabase database,connectionsource connectionsource, int oldversion, int NewVersion) {try{tableutils.droptable (Connectionsource, User.class, true); onCreate (database, connectionsource);} catch (SQLException e) {e.printstacktrace ();}} private static Databasehelper instance;/** * Single case get the helper * * @param context * @return */public static synchronized Databa Sehelper Gethelper (Context context) {if (instance = = null) {synchronized (Databasehelper.class) {if (instance = = null) Instance = new Databasehelper (context);}} return instance;} /** * Get Userdao * * @return * @throws SQLException */public dao<user, integer> Getuserdao () throws Sqlexception{if (Userdao = = null) {Userdao = Getdao (User.class);} return Userdao;} /** * Release resource */@Overridepublic void Close () {super.close (); Userdao = null;}}


here we need to inherit Ormlitesqliteopenhelper, in fact, is indirectly inherited. Sqliteopenhelper

Then you need to implement two methods:

1, onCreate (sqlitedatabase database,connectionsource connectionsource)

To create the table, we directly use the tableutils.createtable provided by Ormlite (Connectionsource, User.class);

2, Onupgrade (sqlitedatabase database, Connectionsource connectionsource, int oldversion, int newversion)

Update table, using tableutils.droptable provided by Ormlite (Connectionsource, User.class, true); Delete Operation ~

After the deletion is complete, do not forget to create the operation: OnCreate (Database, Connectionsource);


Then use a singleton to publish a method of creating an instance, Gethelper to get our help instance;

Finally we may have many tables, each table generally we will write a DAO for operation, here for the sake of simplicity I did not extract, directly written in the helper:

such as the acquisition of Userdao:

/** * Get Userdao *  * @return * @throws SQLException */public dao<user, integer> Getuserdao () throws sqlexception{ if (Userdao = = null) {Userdao = Getdao (User.class);} return Userdao;}

You can then do some of the user's common operations by getting the DAO.

4. Testing

Finally the test, we directly created a test class to test ~ ~ ~

Package Com.zhy.zhy_ormlite.test;import Java.sql.sqlexception;import Java.util.list;import com.zhy.zhy_ Ormlite.bean.user;import Com.zhy.zhy_ormlite.db.databasehelper;import Android.test.androidtestcase;import Android.util.log;public class Ormlitedbtest extends Androidtestcase{public void Testadduser () {User U1 = new User ("Zhy", " 2 b Youth ");D atabasehelper helper = Databasehelper.gethelper (GetContext ()); Try{helper.getuserdao (). Create (u1); u1 = new User ("Zhy2", "2B Youth"), Helper.getuserdao (). Create (u1), u1 = new User ("Zhy3", "2B Youth"); Helper.getuserdao (). Create (U1); U1 = New User ("Zhy4", "2B Youth"); Helper.getuserdao (). Create (u1); u1 = new User ("Zhy5", "2B Youth"); Helper.getuserdao (). Create (U1 ); u1 = new User ("Zhy6", "2B Youth"), Helper.getuserdao (). Create (U1); Testlist ();} catch (SQLException e) {e.printstacktrace ();}} public void Testdeleteuser () {Databasehelper helper = Databasehelper.gethelper (GetContext ()); Try{helper.getuserdao () . Deletebyid (2);} catch (SQLException e) {e.printstacktrace ();}} public void TestupdateuseR () {Databasehelper helper = Databasehelper.gethelper (GetContext ()); Try{user u1 = new User ("Zhy-android", "2B Youth"); U1.setid (3); Helper.getuserdao (). Update (U1); catch (SQLException e) {e.printstacktrace ();}} public void Testlist () {Databasehelper helper = Databasehelper.gethelper (GetContext ()); Try{user u1 = new User (" Zhy-android "," 2B Youth "); U1.setid (2); list<user> users = Helper.getuserdao (). Queryforall (); LOG.E ("TAG", users.tostring ());} catch (SQLException e) {e.printstacktrace ();}}}

A simple test of the next curd, using androidtestcase remember configuration under the Environment ~ ~ ~

It is still very convenient to use, but it is recommended that you, for example, user database operations, extracted separately as Userdao, as follows:

Package Com.zhy.zhy_ormlite.db;import Java.sql.sqlexception;import Android.content.context;import com.zhy.zhy_ Ormlite.bean.user;public class Userdao{private Context Context;public Userdao (context context) {This.context = context;} public void Add (user user) {try{databasehelper.gethelper (context). Getuserdao (). Create (user), and catch (SQLException e) { }}//......}

Note: Ormlite also provides some base class Ormlitebaseactivity,ormlitebaseservice and so on, easy to database operation, here do not consider, after all, the project is very likely to inherit their own baseactvity and the like.


The above is a brief introduction to how to use the Ormlite framework, and the use of the Android Rapid Development Series Ormlite framework will be described in depth.


SOURCE Click to download







Getting started with the Android ormlite framework

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.