Android ORMLite framework entry usage, androidormlite

Source: Internet
Author: User

Android ORMLite framework entry usage, androidormlite

Reprinted please indicate the source:

Databases are used more or less in Android projects. To improve our development efficiency, the database ORM framework is indispensable, especially for apps with extremely frequent database operations; this blog will detail the simple usage of ORMLite.

The following describes how to get started with ORMLite ~

1. Download ORMLite Jar

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

Ps: A friend who cannot access the website will package the jar, source code, doc, and the blog example at the end of the article for you to download.

2. Configure the Bean class

With jar, we directly create a project named zhy_ormlite and copy the jar to libs.

Create a new package: com. zhy. zhy_ormlite.bean, which is used to store the Bean in the project. First, create a 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){ = name;this.desc = desc;}public int getId(){return id;}public void setId(int id){ = id;}public String getName(){return name;}public void setName(String name){ = name;}public String getDesc(){return desc;}public void setDesc(String desc){this.desc = desc;}}

First, add @ DatabaseTable (tableName = "tb_user") to the User class to indicate that this is a table in the database and it is marked as tb_user.

Then add @ DatabaseField (columnName = "name") to the attribute respectively. The value of columnName is the column name of the field in the data.

@ DatabaseField (generatedId = true). generatedId indicates that the id is the primary key and is automatically generated.

3. Write DAO classes

Native database operations must inherit SQLiteOpenHelper. here we need to inherit OrmLiteSqliteOpenHelper. See 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 <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, 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;/*** obtain the Helper *** @ param context * @ return */public static synchronized DatabaseHelper 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 from OrmLiteSqliteOpenHelper, which is actually indirectly inherited from SQLiteOpenHelper

Then we need to implement two methods:

1. onCreate (SQLiteDatabase database, ConnectionSource connectionSource)

Create a table using TableUtils. createTable (connectionSource, User. class) provided by ormlite ~

2. onUpgrade (SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion)

Update the table and use TableUtils. dropTable (connectionSource, User. class, true) provided by ormlite to delete the table ~

After deletion, do not forget to create onCreate (database, connectionSource );

Then, use the singleton to publish a method for creating an instance. getHelper is used to obtain our help instance;

In the end, we may have many tables. Generally, we write a Dao for each table. For simplicity, I didn't extract the table and write it directly in helper:

For example, get UserDao:

/*** Get userDao ** @ return * @ throws SQLException */public Dao <User, Integer> getUserDao () throws SQLException {if (userDao = null) {userDao = getDao (User. class);} return userDao ;}

Then, you can perform some common User operations through the obtained Dao.

4. Test

Finally, we created a test class for testing ~~~

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", "2B "); DatabaseHelper helper = DatabaseHelper. getHelper (getContext (); try {helper. getUserDao (). create (u1); u1 = new User ("zhy2", "2B "); helper. getUserDao (). create (u1); u1 = new User ("zhy3", "2B "); helper. getUserDao (). create (u1); u1 = new User ("zhy4", "2B "); helper. getUserDao (). create (u1); u1 = new User ("zhy5", "2B "); helper. getUserDao (). create (u1); u1 = new User ("zhy6", "2B "); 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 "); 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 "); u1.setId (2); List <User> users = helper. getUserDao (). queryForAll (); Log. e ("TAG", users. toString ();} catch (SQLException e) {e. printStackTrace ();}}}

After a simple test of CURD, use AndroidTestCase to remember to configure the environment ~~~

It is very convenient to use. However, we recommend that you extract UserDao as a separate database for User operations, as shown below:

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);} catch (SQLException e){}}//......}

Note: ORMLite also provides some base classes such as ORMLiteBaseActivity and ORMLiteBaseService to facilitate database operations. We will not consider them here. After all, the project may also need to inherit its own BaseActvity.

The preceding section briefly introduces how to use the ORMLite framework. The use of the ORMLite framework in the Android quick development series will provide an in-depth introduction to its usage.

Download source code

Getting started with Android

This is also possible, but there will be warning. The best use is to add this sentence to the strings file in the values folder <string name = "string_color"> color </string>
Then use android: text = "@ string/string_color" in the layout file"

This can improve the performance and stability. In some cases, this method may even cause compilation errors.

The usage of android this can be explained here.

This current class (activity, etc.) points to the current class.
For example, nextButton. setOnClickListener (this) in the program );
This is equivalent to the Context of the current class, that is, the current
As follows,
NextButton. setOnClickListener (new OnClickListener (){

@ Override
Public void onClick (View v ){
Toast. makeText (TextSwitcher1.this, "here", 5000). show ();
In Toast (context, string, time), you will encounter an error when writing this directly, because your current class is the OnClickListener class. Without losing our Activity class, errors will occur when you write it! Therefore, writing this in the internal class refers to the internal class, not the external class! This is the current. All attributes of TextSwitcher1 can be called after TextSwitcher1.this!
In addition, we are calling some methods. The passed Context is used to pass the current class.


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: 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.