Android 使用ORMLite 操作数据库

首先,到http://ormlite.com/releases/下载相关jar包:ormlite-android-4.48.jarormlite-core-4.48.jar

第一步:继承OrmLiteSqliteOpenHelper类定义一个数据库帮助类;

 

 1 public class MessageBeanHelper extends OrmLiteSqliteOpenHelper {
 2 
 3     private static final String TAG = "MessageBeanHelper";
 4 
 5     // name of the database file for your application -- change to something
 6     // appropriate for your app
 7     private static final String DATABASE_NAME = "smartcareio.db";
 8 
 9     // any time you make changes to your database objects, you may have to
10     // increase the database version
11     private static final int DATABASE_VERSION = 1;
12 
13     // the DAO object we use to access the TaskPackageBean table
14     private Dao<MessageBean, Integer> messageDao = null;
15     private RuntimeExceptionDao<MessageBean, Integer> messageRuntimeDao = null;
16 
17     public MessageBeanHelper(Context context) {
18         super(context, DATABASE_NAME, null, DATABASE_VERSION);
19     }
20 
21     /**
22      * This is called when the database is first created. Usually you should
23      * call createTable statements here to create the tables that will store
24      * your data.
25      */
26     @Override
27     public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
28         try {
29             Log.i(TAG, "onCreate");
30             TableUtils.createTable(connectionSource, MessageBean.class);
31         } catch (SQLException e) {
32             Log.e(TAG, "Can't create database!!!!");
33             throw new RuntimeException(e);
34         }
35     }
36 
37     /**
38      * This is called when your application is upgraded and it has a higher
39      * version number. This allows you to adjust the various data to match the
40      * new version number.
41      */
42     @Override
43     public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource,
44             int oldVersion, int newVersion) {
45         try {
46             Log.i(TAG, "onUpgrade");
47             TableUtils.dropTable(connectionSource, MessageBean.class, true);
48             // after we drop the old databases, we create the new ones
49             onCreate(db, connectionSource);
50         } catch (SQLException e) {
51             Log.e(TAG, "Can't drop databases!!!", e);
52             throw new RuntimeException(e);
53         }
54     }
55     
56     /**
57      * Returns the Database Access Object (DAO) for our MessageBean class.
58      * It will create it or just give the cached value.
59      */
60     public Dao<MessageBean, Integer> getDao() throws SQLException {
61         if (messageDao == null) {
62             messageDao = getDao(MessageBean.class);
63         }
64         return messageDao;
65     }
66     
67     /**
68      * Returns the RuntimeExceptionDao (Database Access Object) version of a Dao
69      * for our MessageBean class. It will create it or just give the cached
70      * value. RuntimeExceptionDao only through RuntimeExceptions.
71      */
72     public RuntimeExceptionDao<MessageBean, Integer> getMessageBeanDao() {
73         if (messageRuntimeDao == null) {
74             messageRuntimeDao = getRuntimeExceptionDao(MessageBean.class);
75         }
76         return messageRuntimeDao;
77     }
78     
79     /**
80      * Close the database connections and clear any cached DAOs.
81      */
82     @Override
83     public void close() {
84         super.close();
85         messageDao = null;
86         messageRuntimeDao = null;
87     }
88 }

 

第二步:定义原始类;

 1 public class Message {
 2 
 3     @Expose
 4     private int messageID;// 留言的id
 5     @Expose
 6     private String filePath; // 文件源路径,包含文件名
 7     @Expose
 8     private float length; // 录音文件的长度
 9 
10     public int getMessageID() {
11         return messageID;
12     }
13 
14     public void setMessageID(int messageID) {
15         this.messageID = messageID;
16     }
17 
18     public String getFilePath() {
19         return filePath;
20     }
21 
22     public void setFilePath(String filePath) {
23         this.filePath = filePath;
24     }
25 
26     public float getLength() {
27         return length;
28     }
29 
30     public void setLength(float length) {
31         this.length = length;
32     }

 

 

 

第三步:定义Bean类,对要持久化的类进行注解,代表一张表,原始类也可以作为bean类,但为了区分原始类用于网络交互,bean类用于数据库交互,这里分开写(记住提供一个默认无参构造)

  @DatabaseTable
1
public class MessageBean { 2 3 @DatabaseField(generatedId = true)//id自增长 4 private int messageID;// 留言的id 5 @DatabaseField 6 private String filePath; // 文件源路径,包含文件名 7 @DatabaseField 8 private float length; // 录音文件的长度 9 10 public MessageBean() {//无参构造 11 } 12 13 public MessageBean(Message message) { 14 CopyFromTaskPackage(message); 15 } 16 17 public void CopyFromTaskPackage(Message message) { 18 messageID = message.getMessageID(); 19 length = message.getLength(); 20 filePath = message.getFilePath(); 21 } 22 23 public Message ToMessage() { 24 Message message = new Message(); 25 message.setMessageID(messageID); 26 message.setFilePath(filePath); 27 message.setLength(length); 28 return message; 29 } 30 31 public int getMessageID() { 32 return messageID; 33 } 34 35 public void setMessageID(int messageID) { 36 this.messageID = messageID; 37 } 38 39 public String getFilePath() { 40 return filePath; 41 } 42 43 public void setFilePath(String filePath) { 44 this.filePath = filePath; 45 } 46 47 public float getLength() { 48 return length; 49 } 50 51 public void setLength(float length) { 52 this.length = length; 53 } 54 55 56 }

 

上面定义了一个套餐对象,我们来看一下它所用到的几个注解: 
@DatabaseTable:表示定义了一个数据表,如果不指定名字,在Android中会以类名作为表名,如message就是SQLite数据库中的表名,我们也可以指定表名,@DatabaseTable(tableName = “tb_message”) 。

DatabaseField:表示定义了数据中的一个字段,id表示数据中的一个主键,如果指定为generatedId,表示自动增长id,我们不需要给它赋值。其他字段,可以使用columnName来指定字段名,canBeNull表示是否为空,这些赋值可以按照以下来指定 
-(id = true, canBeNull = false) 
- (columnName = “name”)

还有更多的注解用法,可以到官网查看它提供的文档。

 

第四步:定义Bean的IO类,增,删,查,改;

 1 public class MessageIo {
 2 
 3     private Context context;
 4     private MessageBeanHelper messageBeanHelper;
 5     private RuntimeExceptionDao<MessageBean, Integer> messageDao;
 6     
 7     public MessageIo(Context context) {
 8         this.context = context;
 9         messageBeanHelper = new MessageBeanHelper(this.context);
10         messageDao = messageBeanHelper.getMessageBeanDao();
11     }
12     
13     public void InsertOrUpdateMessageInfo(Message message) {
14         SmartIoDBLock.Lock.writeLock().lock();
15         messageDao.createOrUpdate(new MessageBean(message));
16         SmartIoDBLock.Lock.writeLock().unlock();
17     }
18     
19     public void DeleteMessage(MessageBean messageBean) {
20         SmartIoDBLock.Lock.writeLock().lock();
21         messageDao.delete(messageBean);
22         SmartIoDBLock.Lock.writeLock().unlock();
23     }
24 
25     public void DeleteMessageById(String messageId) {
26         SmartIoDBLock.Lock.writeLock().lock();
27         try {
28             messageDao.deleteBuilder().where().eq("messageID", messageId).query();
29 //            messageDao.deleteBuilder().delete();
30         } catch (SQLException e) {
31             e.printStackTrace();
32         }
33         SmartIoDBLock.Lock.writeLock().unlock();
34     }
35 
36     public Message LoadMessage(String messageID) {
37         Message rtn = null;
38         List<MessageBean> temp = null;
39         SmartIoDBLock.Lock.writeLock().lock();
40         try {
41             temp = messageDao.queryBuilder().where()
42                     .eq("messageID", messageID).query();
43         } catch (SQLException e) {
44             e.printStackTrace();
45         }
46         SmartIoDBLock.Lock.writeLock().unlock();
47 
48         if (temp != null) {
49             for (MessageBean bean : temp) {
50                 Message taskPackage = bean.ToMessage();
51                 rtn = taskPackage;
52             }
53         }
54         return rtn;
55     }
56 
57     public List<Message> LoadAllMessages() {
58         List<Message> rtn = new ArrayList<Message>();
59         List<MessageBean> temp = null;
60         SmartIoDBLock.Lock.writeLock().lock();
61         temp = messageDao.queryForAll();
62         SmartIoDBLock.Lock.writeLock().unlock();
63 
64         if (temp != null) {
65             for (MessageBean bean : temp) {
66                 Message taskPackage = bean.ToMessage();
67                 rtn.add(taskPackage);
68             }
69         }
70         return rtn;
71     }
72 }

第五步:

具体使用方法:

1 MessageIo messageIo = new MessageIo(MyApplication.getContext());
2 Message message = new Message();
3 message.setFilePath(filePath);
4 message.setLength(seconds);
5 messageIo.InsertOrUpdateMessageInfo(message);

通过网络请求得到的json对象,相关的转化在这里就不详解了。。。。

 
posted @ 2016-03-29 16:57  梅超风awa  阅读(540)  评论(0编辑  收藏  举报