在activity 中使用时初始化View 信息和数据库信息
@Override
protectedvoidonCreate(Bundle savedInstanceState) {
//TODOAuto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initDb();
}
初始化数据库的名字,版本
privatevoidinitDb() {
dbFastControl= DbFastControl.getDbFast();
List<Object>clz_list = newArrayList<Object>();
clz_list.add(User.class);
clz_list.add(News.class);
clz_list.add(NeoContacts.class);
DBConfigconfig = DBConfig.getDBConfig();
config.DB_NAME= "FasterDB.db";
config.DB_VERSION= 1;
dbFastControl.init(this,config, clz_list);
}
publicstaticDbFastControl getDbFast()
{
if(instance== null)
{
synchronized(DbFastControl.class)
{
instance= newDbFastControl();
}
}
returninstance;
}
加载数据库的配置,创建数据库
publicvoidinit(Context ctx, DBConfig dbConfiguration
,List<Object> clz_list) {
this.context= ctx;
this.clz_list= clz_list;
if(dbConfig== null){
dbConfig.DB_NAME= db_name;
dbConfig.DB_VERSION= db_version;
} else{
dbConfig= dbConfiguration;
}
DbFasterSqlite.getInstance(ctx,clz_list);
}
package com.yagang.faster.db; import com.yagang.faster.db.model.NeoContacts; import com.yagang.faster.db.model.News; import com.yagang.faster.db.model.User; import com.yagang.faster.db.util.DBConfig; import com.yagang.faster.inject.core.InjectView; import com.yagang.faster.util.FasterLog; import android.app.Activity; import android.app.ProgressDialog; import android.database.Cursor; import android.os.Bundle; import android.provider.Contacts; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import java.util.ArrayList; import java.util.List; public class DbFastTest extends Activity implements OnClickListener { private DbFastControl dbFastControl = null; private Button btn_add, btn_select = null; private ProgressDialog dialog = null; private Button btn_delete; private Button btn_update; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); initDb(); } private void initView() { btn_add = (Button) findViewById(R.id.btn_add); btn_select = (Button) findViewById(R.id.btn_select); btn_delete = (Button) findViewById(R.id.btn_delete); btn_update = (Button) findViewById(R.id.btn_update); btn_add.setOnClickListener(this); btn_select.setOnClickListener(this); btn_delete.setOnClickListener(this); btn_update.setOnClickListener(this); } private void initDb() { dbFastControl = DbFastControl.getDbFast(); List<Object> clz_list = new ArrayList<Object>(); clz_list.add(User.class); clz_list.add(News.class); clz_list.add(NeoContacts.class); DBConfig config = DBConfig.getDBConfig(); config.DB_NAME = "FasterDB.db"; config.DB_VERSION = 1; dbFastControl.init(this, config, clz_list); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); } @Override public void onClick(View v) { if (v == btn_add) { dialog = new ProgressDialog(this); dialog.setTitle("提示"); dialog.setMessage("正在添加数据.."); dialog.show(); new Thread(new Runnable() { public void run() { int i = 0; for (i = 0; i < 10; i++) { insert(); } } }).start(); } else if (v == btn_select) { dialog = new ProgressDialog(this); dialog.setTitle("提示"); dialog.setMessage("正在查询数据.."); dialog.show(); new Thread(new Runnable() { public void run() { int i = 0; for (i = 0; i < 10; i++) { select(); } } }).start(); } else if (v == btn_delete) { dialog = new ProgressDialog(this); dialog.setTitle("提示"); dialog.setMessage("正在删除数据.."); dialog.show(); new Thread(new Runnable() { public void run() { int i = 0; for (i = 0; i < 10; i++) { delete(); } } }).start(); } else if (v == btn_update) { dialog = new ProgressDialog(this); dialog.setTitle("提示"); dialog.setMessage("正在更新数据.."); dialog.show(); new Thread(new Runnable() { public void run() { int i = 0; for (i = 0; i < 10; i++) { update(); } } }).start(); } } private void insert() { User user = new User(); user.setUid(100); user.setU_name("lihao"); user.setU_pass("5555"); user.setBuy_year(200l); user.setCar_price(50.0); user.setKm(60f); user.setTrue(true); User user2 = new User(); user.setUid(101); user.setU_name("liubi"); user.setU_pass("5555"); user.setBuy_year(200l); user.setCar_price(50.0); user.setKm(60f); user.setTrue(true); NeoContacts contacts1 = new NeoContacts(); contacts1.setContacts_addr("test_contacts_1"); contacts1.setContacts_name("test_bname"); contacts1.setContacts_num("1234567"); List<Object> add_list = new ArrayList<Object>(); add_list.add(user); add_list.add(user2); add_list.add(contacts1); long insertSuccess = dbFastControl.insert(add_list); if (insertSuccess > 0l) { FasterLog.d("addSize = " + insertSuccess); dialog.dismiss(); } } private void select() { List<Object> userList = DbFastControl.getDbFast().queryAll(User.class); if (userList != null && userList.size() > 0) { FasterLog.d("allsize = " + userList.size()); for (int i = 0; i < userList.size(); i++) { Object object = userList.get(i); User user = (User) object; FasterLog.d("userName = " + user.getU_name()); } dialog.dismiss(); } } private void delete() { int userList = DbFastControl.getDbFast().delete(User.class, null, null); FasterLog.d("delete = " + userList); dialog.dismiss(); } private void update() { int userList = DbFastControl.getDbFast().update(User.class, null, null); FasterLog.d("update = " + userList); dialog.dismiss(); } } package com.yagang.faster.db; import com.yagang.faster.db.core.DbFasterSqlite; import com.yagang.faster.db.util.DBConfig; import com.yagang.faster.util.FasterLog; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.provider.CalendarContract.Instances; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; public class DbFast implements IDbFast { private String db_name = "DBFast.db"; private int db_version = 1; private Context context = null; private List<Object> clz_list = null; public static DBConfig dbConfig = DBConfig.getDBConfig(); private SQLiteDatabase db = null; private static DbFast instance = null; protected DbFast() { } public static DbFast getDbFast() { if (instance == null) { synchronized (DbFast.class) { instance = new DbFast(); } } return instance; } public void init(Context ctx, DBConfig dbConfiguration, List<Object> clz_list) { this.context = ctx; this.clz_list = clz_list; if (dbConfig == null) { dbConfig.DB_NAME = db_name; dbConfig.DB_VERSION = db_version; } else { dbConfig = dbConfiguration; } DbFasterSqlite.getInstance(ctx, clz_list); } @Override public synchronized long insert(List<Object> clzs) { long count = -1; db = null; try { db = DbFasterSqlite.getInstance(context, clz_list).getWritableDatabase(); if (clzs != null && db != null && db.isOpen() && !db.isDbLockedByCurrentThread()) { db.beginTransaction(); int size = clzs.size(); for (int i = 0; i < size; i++) { Object clz = clzs.get(i); //如果是增加与删除 得到class必须使用object的getClass()方法 Class<?> c = clz.getClass(); count = db.insert(c.getSimpleName(), null, createContentValue(clz)); } FasterLog.d("count:" + count); db.setTransactionSuccessful(); db.endTransaction(); } } catch (Exception e) { FasterLog.E(DbFast.class, e); if (db != null) { db.close(); db = null; } count = -1; } return count; } @Override public synchronized Object query(Object clz, String where, String[] whereArgs) { Object object = null; try { db = DbFasterSqlite.getInstance(context, clz_list).getReadableDatabase(); if (clz != null && db != null && db.isOpen() && !db.isDbLockedByCurrentThread()) { Class<?> c = (Class<?>) clz; Cursor cursor = db.query(c.getSimpleName(), null, where, whereArgs, null, null, null); List<Object> list = convertCursor(clz, cursor); if (list != null && list.size() > 0) { object = list.get(0); } } } catch (Exception e) { FasterLog.E(DbFast.class, e); object = null; if (db != null) { db.close(); db = null; } } return object; } @Override public synchronized List<Object> queryAll(Object clz) { List<Object> list = null; try { db = DbFasterSqlite.getInstance(context, clz_list).getReadableDatabase(); if (clz != null && db != null && db.isOpen() && !db.isDbLockedByCurrentThread()) { //查询相关如果要获取object的clss直接使用强转即可,因为传入的也是一个.class Class<?> c = (Class<?>) clz; Cursor cursor = db.query(c.getSimpleName(), null, null, null, null, null, null); list = convertCursor(clz, cursor); } } catch (Exception e) { FasterLog.E(DbFast.class, e); list = null; if (db != null) { db.close(); db = null; } } return list; } @Override public synchronized int update(Object clzs, String where, String[] whereArgs) { int count = -1; db = null; try { db = DbFasterSqlite.getInstance(context, clz_list).getWritableDatabase(); if (clzs != null && db != null && db.isOpen() && !db.isDbLockedByCurrentThread()) { // 如果添加和修改数据库,调用clz.getClass得到类 // 如果是查询和删除,需要直接强转 Class<?> c = clzs.getClass(); count = db.update(c.getSimpleName(), createContentValue(clzs), where, whereArgs); } } catch (Exception e) { FasterLog.E(DbFast.class, e); if (db != null) { db.close(); db = null; } count = -1; } return count; } @Override public synchronized int delete(Object clz, String where, String[] whereArgs) { int count = -1; db = null; try { db = DbFasterSqlite.getInstance(context, clz_list).getWritableDatabase(); if (clz != null && db != null && db.isOpen() && !db.isDbLockedByCurrentThread()) { // 如果添加和修改数据库,调用clz.getClass得到类 // 如果是查询和删除,需要直接强转 Class<?> c = (Class<?>) clz; count = db.delete(c.getSimpleName(), where, whereArgs); } } catch (Exception e) { FasterLog.E(DbFast.class, e); count = -1; if (db != null) { db.close(); db = null; } } return count; } /** * 将要插入的对象转换为contentValue对象 * @param clz * @return */ private ContentValues createContentValue(Object clz) { ContentValues cv = new ContentValues(); try { //因为clz是一个对象,是有值的 //获取他的class,则要使用getClass,而不是强转 Class<?> c = clz.getClass(); Field[] fields = c.getDeclaredFields(); if (fields != null && fields.length > 0) { for (int i = 0; i < fields.length; i++) { Field f = fields[i]; // get field author int t_interview_author = f.getModifiers(); if (t_interview_author == Modifier.PRIVATE) { // 允许此属性被访问 f.setAccessible(true); // get 属性的 name String t_name = f.getName(); // get 属性的值 Object value = f.get(clz); // get 属性的类型 String t_type = f.getType().getSimpleName(); if (t_type != null && t_type.trim().length() > 0) { if (t_type.toLowerCase().equals("string")) { String v = (String) value; cv.put(t_name, v); } else if (t_type.toLowerCase().equals("float")) { float float_v = (Float) value; cv.put(t_name, float_v); } else if (t_type.toLowerCase().equals("long")) { long long_v = (Long) value; cv.put(t_name, long_v); } else if (t_type.toLowerCase().equals("int") || t_type.toLowerCase().equals("integer")) { String v = String.valueOf(value); int int_v = Integer.valueOf(v); cv.put(t_name, int_v); } else if (t_type.toLowerCase().equals("double")) { double double_v = (Double) value; cv.put(t_name, double_v); } else if (t_type.toLowerCase().equals("boolean")) { // 因为查询中cursor没有布尔值 所以存储的时候讲布尔值转化为 0和1 // ture为1 false为0 int boolean_value = 0; boolean boolean_v = (Boolean) value; if (boolean_v) { boolean_value = 1; } else { boolean_value = 0; } cv.put(t_name, boolean_value); } else if (t_type.toLowerCase().equals("byte")) { byte byte_v = (Byte) value; cv.put(t_name, byte_v); } else if (t_type.toLowerCase().equals("byte[]")) { byte[] bytes_v = (byte[]) value; cv.put(t_name, bytes_v); } else { cv.put(t_name, (String) value); } } } } } } catch (Exception e) { FasterLog.E(DbFast.class, e); cv = null; } return cv; } /** * 将查询到的cursor转换为查询类的实体集合 * @param clz 要查询的表(以class显示) * @param cursor * @return */ private List<Object> convertCursor(Object clz, Cursor cursor) { List<Object> list = null; Object newInstance = null; try { list = new ArrayList<Object>(); cursor.moveToFirst(); while (!cursor.isAfterLast()) { //将object转换为 class //如果是查询相关的,直接强转,因为此时clz也是一个.class的类 Class<?> c = (Class<?>) clz; //创建一个clz类的对象 newInstance = Class.forName(c.getCanonicalName()).newInstance(); //获取这个类里的所有的属性 Field[] fields = c.getDeclaredFields(); if (fields != null && fields.length > 0) { for (int i = 0; i < fields.length; i++) { Field f = fields[i]; // 获取属性的权限,只要private私有的 int t_interview_author = f.getModifiers(); if (t_interview_author == Modifier.PRIVATE) { // 允许此属性被访问 f.setAccessible(true); // get 属性的 name String t_name = f.getName(); // get 属性的类型 String t_type = f.getType().getSimpleName(); if (t_type != null && t_type.trim().length() > 0) { if (t_type.toLowerCase().equals("string")) { String value = cursor.getString(cursor.getColumnIndex(t_name)); if (value != null) { f.set(newInstance, value); } } else if (t_type.toLowerCase().equals("float")) { float value = cursor.getFloat(cursor.getColumnIndex(t_name)); f.setFloat(newInstance, value); } else if (t_type.toLowerCase().equals("long")) { long value = cursor.getLong(cursor.getColumnIndex(t_name)); f.setLong(newInstance, value); } else if (t_type.toLowerCase().equals("int") || t_type.toLowerCase().equals("integer")) { int value = cursor.getInt(cursor.getColumnIndex(t_name)); f.setInt(newInstance, value); } else if (t_type.toLowerCase().equals("double")) { double value = cursor.getDouble(cursor.getColumnIndex(t_name)); f.setDouble(newInstance, value); } else if (t_type.toLowerCase().equals("boolean")) { int value = cursor.getInt(cursor.getColumnIndex(t_name)); // 因为cursor中没有布尔值,所以我们再插入数据的时候 // 将布尔值转化为数字 0 和 1 // true 为1 // false 为0 if (value == 1) { f.setBoolean(newInstance, true); } else { f.setBoolean(newInstance, false); } } else if (t_type.toLowerCase().equals("byte[]")) { byte[] value = cursor.getBlob(cursor.getColumnIndex(t_name)); f.set(newInstance, value); } else { String value = cursor.getString(cursor.getColumnIndex(t_name)); f.set(newInstance, value); } } } } } list.add(newInstance); cursor.moveToNext(); } cursor.close(); cursor = null; } catch (Exception e) { FasterLog.E(DbFast.class, e); list = null; if (cursor != null) { cursor.close(); cursor = null; } } return list; } } 源码 : http://download.csdn.net/detail/tianyeming/9354293