唠嗑
Android app开发,网上资料一大把, 但是能够附带demo的很少,并且谁能推荐几个好的Andorid app 开源代码网站不。
iOS app 就有很多开源代码网站。(例如 cocoa4app)
引言
Android 持久化数据库,sqlite的二次封装,在我理解里也是有两种思路做法。
1.通用表:建立一张表(ID,Obj,time) 一个id,一个obj加一个时间戳。
2.字段表: 这可能就存在多张表,例如(用户表,历史搜索表等),每个表的属性字段,吧唧吧唧写一堆。
(备注: 通用表省去了,数据库的升级,但是查询却不方便了。字段表倘若哪天字段不够用了,则版本要升级,版本升级并不是删除表在重新建个表,这样原来的数据就没了。思路是老表重命名,建立新表,老表数据复制到新表里,删除老表)
有问题可以留言,且行且摸索。
内容一 ,通用表
DbHelper.java
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.Date;
public class DbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME="default.db";
private static final int VERSION = 1;
//单例模式
private static DbHelper dbHelper;
public static synchronized DbHelper getInstance(Context context){
if(dbHelper==null)
dbHelper=new DbHelper(context);
return dbHelper;
}
private DbHelper(Context context) {
super(context,DATABASE_NAME,null,VERSION);
}
private DbHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context,name,factory,version);
}
@Override
public void onCreate(SQLiteDatabase db) {
//public String itemId;
//public String itemObject;
//public Date timestamp;
// DbItem 表
String sql="create table if not exists DbItem (" +
"_id integer primary key," +
"itemId text," +
"itemObject text," +
"timestamp Date" +
")";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//String sql="drop table DbItem";
//db.execSQL(sql);
//onCreate(db);
}
}
DbItem.java
import java.util.Date;
public class DbItem {
public String itemId;
public String itemObject;
public Integer timestamp;
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String getItemObject() {
return itemObject;
}
public void setItemObject(String itemObject) {
this.itemObject = itemObject;
}
public Integer getTimestamp() {
return timestamp;
}
public void setTimestamp(Integer timestamp) {
this.timestamp = timestamp;
}
}
DbUtils.java
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.example.mzysqlite.Util.DBUtils;
import com.example.mzysqlite.Util.tb_stu;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.IDN;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class DbUtils {
public static final String TAG = "DbUtils";
public String DB_NAME = "DbItem";
//声明SQLite数据库
SQLiteDatabase sdb;
//创建构造方法并实例化SQLiteDatabase对象
public DbUtils(Context context){
sdb=DbHelper.getInstance(context).getReadableDatabase();
}
//调用SQLiteDatabase对象的 添加 方法进行数据添加,返回值为添加数据行的ID
public long insert(String tableName, ContentValues values){
long id=sdb.insert(tableName,null,values);
Log.e(TAG,"=========插入代码:" + id);
return id;
}
//调用SQLiteDatabase对象的 修改 方法进行数据添加,返回值为修改数据行的ID
public int update(String tableName,ContentValues values,String where,String[] whereArgs){
int i=sdb.update(tableName,values,where,whereArgs);
Log.e(TAG,"=========更新代码:" + i);
return i;
}
//调用SQLiteDatabase对象的 删除 方法进行数据添加,返回值为删除行
public int delete(String tableName,String where,String[] whereArgs){
int i=sdb.delete(tableName,where,whereArgs);
Log.e(TAG,"============删除代码:" + i);
return i;
}
//调用SQLiteDatabase对象的 查询 方法进行数据添加,返回值为游标
public Cursor query(String tableName, String[] columns, String selection, String[] selectArgs, String groupBy, String having, String orderBy, String limit){
Cursor cursor = sdb.query(tableName,columns,selection,selectArgs,groupBy,having,orderBy,limit);
//List<tb_stu>list = getEntity(cursor, tb_stu.class);
return cursor;
}
/**
* 从数据库得到实体类
*
* @param cursor
* @param clazz
* @param <T>
* @return
*/
public <T> List<T> getEntity(Cursor cursor, Class<T> clazz) {
List<T> list = new ArrayList<>();
try {
if (cursor != null && cursor.moveToFirst()) {
do {
Field[] fields = clazz.getDeclaredFields();
T modeClass = clazz.newInstance();
for (Field field : fields) {
if (!isRedundancy(field.getName())) {
//Log.e(TAG,"=======name:" + field.getName());
Class<?> cursorClass = cursor.getClass();
String columnMethodName = getColumnMethodName(field.getType()); //拿属性
Method cursorMethod = cursorClass.getMethod(columnMethodName, int.class);
Object value = cursorMethod.invoke(cursor, cursor.getColumnIndex(field.getName())); //拿值
if (field.getType() == boolean.class || field.getType() == Boolean.class) {
if ("0".equals(String.valueOf(value))) {
value = false;
}
else{
value = true;
}
}
else if (field.getType() == char.class || field.getType() == Character.class) {
value = ((String) value).charAt(0);
}
else if (field.getType() == Date.class) {
long date = (long) value;
if (date <= 0) {
value = null;
}
else {
value = new Date(date);
}
}
String methodName = makeSetterMethodName(field); //set成员
Method method = clazz.getDeclaredMethod(methodName, field.getType());
method.invoke(modeClass, value);
//Log.e(TAG,"=======method:" + method);
}
}
list.add(modeClass);
} while (cursor.moveToNext());
}
} catch (Exception e) {
Log.e(TAG,"======走catch");
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
return list;
}
private Boolean isRedundancy(String fieldName ){
if (fieldName.equals("$change") || fieldName.equals("serialVersionUID")) {
return true;
}
return false;
}
private String getColumnMethodName(Class<?> fieldType) {
String typeName;
if (fieldType.isPrimitive()) {
typeName = DBUtils.capitalize(fieldType.getName());
} else {
typeName = fieldType.getSimpleName();
}
String methodName = "get" + typeName;
if ("getBoolean".equals(methodName)) {
methodName = "getInt";
} else if ("getChar".equals(methodName) || "getCharacter".equals(methodName)) {
methodName = "getString";
} else if ("getDate".equals(methodName)) {
methodName = "getLong";
} else if ("getInteger".equals(methodName)) {
methodName = "getInt";
}
return methodName;
}
private String makeSetterMethodName(Field field) {
String setterMethodName;
String setterMethodPrefix = "set";
if (isPrimitiveBooleanType(field) && field.getName().matches("^is[A-Z]{1}.*$")) {
setterMethodName = setterMethodPrefix + field.getName().substring(2);
} else if (field.getName().matches("^[a-z]{1}[A-Z]{1}.*")) {
setterMethodName = setterMethodPrefix + field.getName();
} else {
setterMethodName = setterMethodPrefix + DBUtils.capitalize(field.getName());
}
return setterMethodName;
}
private boolean isPrimitiveBooleanType(Field field) {
Class<?> fieldType = field.getType();
if ("boolean".equals(fieldType.getName())) {
return true;
}
return false;
}
}
内容二,字段表
这个有时间做。