为了以后的项目使用Android数据库更方便,自已写了一个小的应用框架,不知道算不算称得上框架,反正自已用起来觉得还是挺方便的,参考Hibernate了应用思想。
业务介绍
1、建一个数据库madfiger.db
2、建一个用户表UserInfo,包含一些用户基本字段
好了那么我们现在来实现吧
1、新建UserInfo实体类,继承AbstractBaseModel,UserInfo的类名为数据库表名,字段分别为实现了Get与Set方式的实性字段;
UserInfo代码如下:
package cn.company.android.project.model; import java.util.Calendar; import java.util.Date; import java.util.Locale; import cn.madfinger.android.core.AbstractBaseModel; import cn.madfinger.android.core.util.DateUtils; public class UserInfo extends AbstractBaseModel{ private static final long serialVersionUID = -7079062473198239915L; private String id; private String username; private String password; private String birthday; private int gender; private float weight; private Date createTime=DateUtils.long2Date(Calendar.getInstance(Locale.CHINESE).getTimeInMillis()); public UserInfo(){ super(); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public int getGender() { return gender; } public void setGender(int gender) { this.gender = gender; } public float getWeight() { return weight; } public void setWeight(float weight) { this.weight = weight; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } }
AbstractBaseModel代码如下:
package cn.madfinger.android.core; import java.io.Serializable; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.json.JSONObject; import android.util.Log; /** * 实体模型基类 * * @author wiley */ public abstract class AbstractBaseModel implements Serializable { private static final long serialVersionUID = -4685989463430616599L; private static String TAG = AbstractBaseModel.class.getSimpleName(); private static Map<String, String> TYPES = new HashMap<String, String>(); static { TYPES.put("date", "TEXT"); TYPES.put("string", "TEXT"); TYPES.put("integer", "INTEGER"); TYPES.put("int", "INTEGER"); TYPES.put("short", "INTEGER"); TYPES.put("long", "INTEGER"); TYPES.put("float", "REAL"); TYPES.put("double", "REAL"); } public AbstractBaseModel() { TAG = this.getClass().getSimpleName(); } public abstract String getId(); public abstract void setId(String id); public Set<String> toFieldSet(){ return this.toFieldMap().keySet(); } public Map<String, String> toFieldMap() { Map<String, String> fieldMap = new HashMap<String, String>(); Method[] methods = this.getClass().getMethods(); try { String propertyName; String typeString; for (Method method : methods) { String methodName = method.getName(); if (!methodName.startsWith("get") || methodName.equalsIgnoreCase("getClass") || methodName.equalsIgnoreCase("get")) continue; typeString = method.getReturnType().getSimpleName(); propertyName = methodName.substring(3); fieldMap.put(propertyName, typeString); } } catch (Exception e) { Log.e(TAG, e.getMessage()); } return fieldMap; } public String toCreateTableString() { StringBuilder sb = new StringBuilder(); sb.append("CREATE TABLE "); sb.append(this.getClass().getSimpleName()); sb.append(" ("); int i = 0; Map<String, String> fieldMap = toFieldMap(); Iterator<String> it = fieldMap.keySet().iterator(); while (it.hasNext()) { String field = (String) it.next(); String type = fieldMap.get(field).toLowerCase(); if (i++ != 0) sb.append(","); sb.append(field.toUpperCase()); sb.append(" " + (TYPES.containsKey(type)?TYPES.get(type):"NONE")); if (field.equalsIgnoreCase("id")) sb.append(" PRIMARY KEY"); } sb.append(");"); return sb.toString(); } public String toJSONString() { return this.toJSON().toString(); } public JSONObject toJSON() { Method[] methods = this.getClass().getMethods(); JSONObject json = new JSONObject(); Object propertyValue; String propertyName; try { for (Method method : methods) { String methodName = method.getName(); if (!methodName.startsWith("get") || methodName.equalsIgnoreCase("getClass") || methodName.equalsIgnoreCase("get")) continue; propertyValue = method.invoke(this, new Object[] {}); propertyName = methodName.substring(3); propertyName = Character.toLowerCase(propertyName.charAt(0)) + propertyName.substring(1); json.put(propertyName, propertyValue); } } catch (Exception e) { Log.e(TAG, e.getMessage()); } return json; } }
实体类新建后配置Sqlite.xml,此文件位与res/string下
<?xml version="1.0" encoding="utf-8"?> <resources> <!-- 数据库版本 --> <string name="database_version">1</string> <!-- 数据库名称 --> <string name="database_name">madfinger.db</string> <!-- 数据表对应实列 --> <string-array name="model_beans"> <item>cn.company.android.project.model.UserInfo</item> </string-array> </resources>
在软件启动时new SqlitHelper,那么在数据库与表将被自动新建,若需要新建多张表的话只需要新建多个继承AbstractBaseModel类的实体类,并添加至sqlite.xml中即可
下面我再将sqlitHelper贴出来
package cn.madfinger.android.core; import java.util.LinkedList; import java.util.List; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import cn.company.android.project.R; import cn.madfinger.android.core.util.StrUtils; /** * 数据库初始化 * @author wiley * */ public class SqliteHelper { private static final String TAG = SqliteHelper.class.getSimpleName(); private static SQLiteDatabase mWriterHandler; private static SQLiteDatabase mReaderHandler; private static int mVersion; private static String mDatabase; public static List<Class<? extends AbstractBaseModel>> mBeanList = new LinkedList<Class<? extends AbstractBaseModel>>(); private DatabaseHelper mDBHelper; @SuppressWarnings("unchecked") public SqliteHelper(Context context) { Log.i(TAG, "new SqliteHelper"); mVersion=StrUtils.str2int(context.getResources().getString(R.string.database_version), 1); mDatabase=StrUtils.null2string(context.getResources().getString(R.string.database_name), "madfinger.db"); String[] modelBeans=context.getResources().getStringArray(R.array.model_beans); if(null!=modelBeans){ for(String modelBean:modelBeans){ try { mBeanList.add((Class<? extends AbstractBaseModel>)Class.forName(modelBean)); } catch (ClassNotFoundException e) { Log.d(TAG, "",e); } } } //初始化数据库 if(null!=mBeanList&&mBeanList.size()>0){ mDBHelper = new DatabaseHelper(context); mWriterHandler=mDBHelper.getWritableDatabase(); } } public SQLiteDatabase getWriterHandler() { if(null==mWriterHandler) mWriterHandler=mDBHelper.getWritableDatabase(); return mWriterHandler; } public SQLiteDatabase getReaderHandler() { if(null==mReaderHandler) mReaderHandler=mDBHelper.getWritableDatabase(); return mReaderHandler; } public void release() { if (null != mWriterHandler) { mWriterHandler.close(); mWriterHandler = null; } if(null!=mReaderHandler){ mReaderHandler.close(); mReaderHandler=null; } } private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context,mDatabase , null, mVersion); } @Override public void onCreate(SQLiteDatabase db) { Log.i(TAG, "onCreate "); createTable(db); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.i(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); // 删除旧表格 deleteTable(db); // 创建新表 createTable(db); } @Override public void onOpen(SQLiteDatabase db) { super.onOpen(db); Log.i(TAG, "onOpen "); } /* * 创建所有表 */ private void createTable(SQLiteDatabase db) { Log.i(TAG, "createTable begin"); for(Class<? extends AbstractBaseModel> clazz:mBeanList){ try { String sqlString = clazz.newInstance().toCreateTableString(); Log.i(TAG, sqlString); db.execSQL(sqlString); } catch (IllegalAccessException e) { Log.e(TAG, "",e); } catch (InstantiationException e) { Log.e(TAG, "",e); } } Log.i(TAG, "createTable end"); } /* * 删除所有表 */ private void deleteTable(SQLiteDatabase db) { Log.i(TAG, "deleteTable begin"); String sql = "DROP TABLE IF EXISTS "; for(Class<? extends AbstractBaseModel> clazz:mBeanList){ Log.i(TAG, sql + clazz.getSimpleName()); db.execSQL(sql + clazz.getSimpleName()); } Log.i(TAG, "deleteTable end"); } } }
数据库操作将在后一章节中分享给大家