首先介绍一下OrmLite:ORM Lite是把对象Java对象映射到关系型数据库的工具,为把Java对象持久化到SQL数据库提供简单的轻量化的功能。

Object Relational Mapping Lite (ORM Lite) provides some simple, lightweight functionality for persisting Java objects to SQL databases while avoiding the complexity and overhead of more standard ORM packages.

       JPA(Java Persistence API)已经是JAVAEE持久化的标准,相关的产品中还有Hibernate。

本文以一个文章(article)的信息实例程序来展示如何使用ormlite for android的第三方组件来开发Sqlite的C[增加],R[查询],U[更新],D[查询]应用程序,以便更方便的对sqlite数据库的操作。我们先看下程序的结构图:


其中包com.strongunion.ormlite.model下Article.java为实体类,包com.strongunion.ormlite.services下DatabaseHelper.java为数据库辅助类,包com.strongunion.ormlite下的MainActivity.java是界面信息类。同时我们别忘了在根目录下创建一个libs的文件夹,把第三方组件包ormlite-android-版本号.jar ,ormlite-core-版本号.jar放到libs文件夹下就OK了。

Because of the lack of official support for JDBC in Android OS, ORMLite makes direct calls to the Android database APIs to access SQLite databases. You should make sure that you have downloaded and are depending on the ormlite-core.jar and ormlite-android.jar files, but not the ormlite-jdbc.jar version.

因为Android OS没有官方支持JDBC, 所以ORMLite可以直接通过APIs来访问SQLite数据库,所以我们不需要jdbc的jar包。

ORMLite的jar包下载地址和ORMLite的Home首页地址如下:

jar包下载地址:http://ormlite.com/releases/

ORMLite首页:http://ormlite.com/


Article的代码如下图:

package com.strongunion.ormlite.model;


import java.util.Date;


import com.j256.ormlite.dao.ForeignCollection;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.field.ForeignCollectionField;
import com.j256.ormlite.table.DatabaseTable;


@DatabaseTable
public class Article {
@DatabaseField(generatedId = true)
private int id;
@DatabaseField
private String content;
public String getContent() {
return content;
}


public void setContent(String content) {
this.content = content;
}


public Date getPublishedDate() {
return publishedDate;
}


public void setPublishedDate(Date publishedDate) {
this.publishedDate = publishedDate;
}


@DatabaseField
private Date publishedDate;


/*@ForeignCollectionField(eager = true)
ForeignCollection comments;*/


public Article() {
}


}

实体类代码的注意事项:你需要增加 @DatabaseTable 这个注解在每一个类的上边(这个注解是选的,可以更改表名),注解@DatabaseField 增加到每一个需要保存到数据库表中的属性的上边。


DatabaseHelper的代码如下:

package com.strongunion.ormlite.services;


import java.sql.SQLException;


import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;


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.strongunion.ormlite.model.Article;
import com.strongunion.ormlite.model.Comment;


public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

public static final String TAG = "DatabaseHelper";

public static final String DATABASE_NAME = "blog.db";
public static final int DATABASE_VERSION = 1;



 private static DatabaseHelper instance;


 /**
  * @param c
  *          A context to use when initializing the database for the first
  *          time.
  * @return A single instance of DatabaseHelper.
  */
 public static synchronized DatabaseHelper getInstance(Context c) {
   if (instance == null)
     instance = new DatabaseHelper(c);


   return instance;
 }


public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}


/**
* Returns the Database Access Object (DAO) for our Article class. It will create it or just give the cached
* value.
*/
public Dao geAritcletDao() throws SQLException {
return getDao(Article.class);

}


/**
* Returns the Database Access Object (DAO) for our Article class. It will create it or just give the cached
* value.
*/
public Dao geCommentDao() throws SQLException {
return getDao(Comment.class);

}
@Override
public void onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource) {


try {
TableUtils.createTable(connectionSource, Article.class);
TableUtils.createTable(connectionSource, Comment.class);
} catch (SQLException e) {
 Log.e(TAG, "Unable to create tables.", e);
 
}

}


@Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
try {
TableUtils.clearTable(connectionSource, Comment.class);
TableUtils.clearTable(connectionSource, Article.class);
onCreate(database, connectionSource);
} catch (SQLException e) {
Log.e(TAG, "Unable to update tables.", e);
}

}


}

DataHelper代码的注意事项:我们的dataHelper继承OrmLiteSqliteOpenHelper这个类. 重写它的onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource)创建数据库方法onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion)数据库升级方法onCreate creates the database when your app is first installed while onUpgrade handles the upgrading of the database tables when you upgrade your app to a new version

还根据不同的Model实体类来得到相应的Dao来对实体类进行操作(增删改查)等。



MainActivity 的代码如下:

package com.strongunion.ormlite;


import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;


import com.j256.ormlite.dao.Dao;
import com.strongunion.ormlite.model.Article;
import com.strongunion.ormlite.services.DatabaseHelper;


public class MainActivity extends Activity {


ListView articlesListView;


private List articles;

Dao articleDao;

DatabaseHelper dataHelper;

ArticlesAdapter adpater;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
dataHelper = DatabaseHelper.getInstance(this);
articleDao = dataHelper.geAritcletDao();
articles = articleDao.queryForAll();
System.out.println("articles size=========" + articles.size());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
articlesListView = (ListView) findViewById(R.id.listView);
articlesListView.setEmptyView(findViewById(R.id.emptyView));
adpater = new ArticlesAdapter(articles);
articlesListView.setAdapter(adpater);
articlesListView.setOnItemLongClickListener(new OnItemLongClickListener() {


@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
opearteArticlePrompt(position);
return false;
}
});
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_article_adding) {
addArticlePrompt();
}
return super.onOptionsItemSelected(item);
}


private void addArticlePrompt() {
View body = LayoutInflater.from(this).inflate(R.layout.article_dialog,
null);
final EditText articleEditText = (EditText) body
.findViewById(R.id.article);


new AlertDialog.Builder(this)
.setTitle("Add Article")
.setView(body)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(
DialogInterface dialogInterface, int i) {
String comments = articleEditText.getText()
.toString().trim();
if (!comments.equals("")) {
// insertComment(name, comments);
Article article = new Article();
article.setContent(comments);
article.setPublishedDate(new Date());
try {
articleDao.create(article);
} catch (SQLException e) {
Log.d("MainActivity", "article add failure");
}
queryListViewItem();
}
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(
DialogInterface dialogInterface, int i) {
// do nothing
}
}).show();
}


private void opearteArticlePrompt(final int position) {
View body = LayoutInflater.from(this).inflate(R.layout.article_dialog,
null);
final EditText articleEditText = (EditText) body
.findViewById(R.id.article);
final Article article = articles.get(position);
articleEditText.setText(article.getContent());


new AlertDialog.Builder(this)
.setTitle("Opearate Article")
.setView(body)
.setPositiveButton(R.string.modification,
new DialogInterface.OnClickListener() {
@Override
public void onClick(
DialogInterface dialogInterface, int i) {
String comments = articleEditText.getText()
.toString().trim();
if (!comments.equals("")) {
article.setContent(comments);
article.setPublishedDate(new Date());
try {
articleDao.update(article);
} catch (SQLException e) {
Log.d("MainActivity", "article add failure");
}
queryListViewItem();
}
}
})
.setNeutralButton(R.string.delete, new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
try {
articleDao.delete(article);
} catch (SQLException e) {
Log.d("MainActivity", "article add failure");
}
queryListViewItem();
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(
DialogInterface dialogInterface, int i) {
// do nothing
}
}).show();
}

private void queryListViewItem(){  
       try {  
           //查询所有的记录项  
           articles = articleDao.queryForAll();  
           System.out.println("articles 2 size=========" + articles.size());
           adpater.setArticlesList(articles);
           adpater.notifyDataSetChanged();
       } catch (SQLException e) {  
           e.printStackTrace();  
       }  
   }  


class ArticlesAdapter extends BaseAdapter{  
         
       private List articlesList;  
       public void setArticlesList(List articlesList) {
this.articlesList = articlesList;
}


SimpleDateFormat formatter = new SimpleDateFormat(
               "'Created on' M/d/yyyy h:mm a");
         
       public ArticlesAdapter(List students){  
           super();  
           this.articlesList = students;  
       }  
       

 
       @Override  
       public int getCount() {  
           return articlesList.size();  
       }  
 
       @Override  
       public Article getItem(int position) {  
           return articlesList.get(position);  
       }  
 
       @Override  
       public long getItemId(int position) {  
           return position;  
       }  
 
       @Override  
       public View getView(int position, View convertView, ViewGroup parent) {  
           ViewHolder holder;  
           if(convertView == null){  
               LayoutInflater mInflater = LayoutInflater.from(MainActivity.this); 
               convertView = mInflater.inflate(R.layout.list_item, null);  
               holder = new ViewHolder();  
               holder.content = (TextView)convertView.findViewById(R.id.list_complex_title);  
               holder.publishedDate = (TextView)convertView.findViewById(R.id.list_complex_caption);  
               convertView.setTag(holder);  
           }else{  
               holder = (ViewHolder)convertView.getTag();  
           }  
             
          
           Article objStu = articlesList.get(position);  
           holder.content.setText(objStu.getContent());  
           holder.publishedDate.setText(formatter.format(objStu.getPublishedDate()));  
             
           return convertView;  
       }  
         
   }  
     
   static class ViewHolder{  
       TextView content;  
       TextView publishedDate;  
   }  


}


MainActivity的注意事项:MainActivity是应用的主界面,点击菜单中的“Add article”输入article的内容之后点击确定,可以增加一个Article。长按某个列表中的item,可以对一个article进行更改删除。


程序运行图解如下:

Step1,程序没有数据的时候界面:


Step2,增加一个Article的界面:


Step3,选中一个article,对这个article进行删除,更改的界面如下:




布局的内容比较简单,在这个就不贴代码了。


希望对大家有所帮助。


更多相关文章

  1. Android实现关机重启的方法
  2. ndk生成ARM汇编(附代码)
  3. Android(安卓)M新控件知识整理
  4. Android实现录屏和截屏功能
  5. Android(Java):ndk开发
  6. Android(安卓)当媒体变更后,通知其他应用重新扫描
  7. More than one file was found with OS independent path 'lib/a
  8. android HTTP 登陆链接Mysql数据库实现登陆
  9. Didn't find class "androidx.core.content.FileProvider" on pa

随机推荐

  1. android:drawableLeft的Button不能切换图
  2. Eclipse 开发 Android, Hello FormStuff(
  3. Android中对话框的使用
  4. 拨云见日---android异步消息机制源码分析
  5. android 4.0 cts
  6. Android SQLiter cursor的使用
  7. Ubuntu android studio 调试 android wea
  8. android中TextView中文字体粗体的方法 (a
  9. Configuration on demand is not support
  10. android使用两种方式注册receiver