1、实体类的注解(activeandroid框架:实现orm操作)
import java.io.Serializable;
import com.activeandroid.Model;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;
@Table(name = "in_cart")
public class InCart extends Model implements Serializable, Cloneable {
/**
*
*/
private static final long serialVersionUID = -3584698829991048916L;
@Column
String goodsId; //id
@Column
String goodsName; //名称
@Column
String goodsIcon; //图片
@Column
String goodsType; //种类
@Column
double goodsPrice; //价格
@Column
String goodsPercent; //好评
@Column
int goodsComment; //评论人数
@Column
int isPhone; //是否手机专享
@Column
int isFavor; //是否已关注
@Column
int num; //购物车中数量
public InCart(){}
public InCart(String goodsId, String goodsName, String goodsIcon,
String goodsType, double goodsPrice, String goodsPercent,
int goodsComment, int isPhone, int isFavor, int num) {
super();
this.goodsId = goodsId;
this.goodsName = goodsName;
this.goodsIcon = goodsIcon;
this.goodsType = goodsType;
this.goodsPrice = goodsPrice;
this.goodsPercent = goodsPercent;
this.goodsComment = goodsComment;
this.isPhone = isPhone;
this.isFavor = isFavor;
this.num = num;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + goodsComment;
result = prime * result
+ ((goodsIcon == null) ? 0 : goodsIcon.hashCode());
result = prime * result + ((goodsId == null) ? 0 : goodsId.hashCode());
result = prime * result
+ ((goodsName == null) ? 0 : goodsName.hashCode());
result = prime * result
+ ((goodsPercent == null) ? 0 : goodsPercent.hashCode());
long temp;
temp = Double.doubleToLongBits(goodsPrice);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result
+ ((goodsType == null) ? 0 : goodsType.hashCode());
result = prime * result + isFavor;
result = prime * result + isPhone;
result = prime * result + num;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
InCart other = (InCart) obj;
if (goodsComment != other.goodsComment)
return false;
if (goodsIcon == null) {
if (other.goodsIcon != null)
return false;
} else if (!goodsIcon.equals(other.goodsIcon))
return false;
if (goodsId == null) {
if (other.goodsId != null)
return false;
} else if (!goodsId.equals(other.goodsId))
return false;
if (goodsName == null) {
if (other.goodsName != null)
return false;
} else if (!goodsName.equals(other.goodsName))
return false;
if (goodsPercent == null) {
if (other.goodsPercent != null)
return false;
} else if (!goodsPercent.equals(other.goodsPercent))
return false;
if (Double.doubleToLongBits(goodsPrice) != Double
.doubleToLongBits(other.goodsPrice))
return false;
if (goodsType == null) {
if (other.goodsType != null)
return false;
} else if (!goodsType.equals(other.goodsType))
return false;
if (isFavor != other.isFavor)
return false;
if (isPhone != other.isPhone)
return false;
if (num != other.num)
return false;
return true;
}
public String getGoodsId() {
return goodsId;
}
public void setGoodsId(String goodsId) {
this.goodsId = goodsId;
}
public String getGoodsName() {
return goodsName;
}
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
}
public String getGoodsIcon() {
return goodsIcon;
}
public void setGoodsIcon(String goodsIcon) {
this.goodsIcon = goodsIcon;
}
public String getGoodsType() {
return goodsType;
}
public void setGoodsType(String goodsType) {
this.goodsType = goodsType;
}
public double getGoodsPrice() {
return goodsPrice;
}
public void setGoodsPrice(double goodsPrice) {
this.goodsPrice = goodsPrice;
}
public String getGoodsPercent() {
return goodsPercent;
}
public void setGoodsPercent(String goodsPercent) {
this.goodsPercent = goodsPercent;
}
public int getGoodsComment() {
return goodsComment;
}
public void setGoodsComment(int goodsComment) {
this.goodsComment = goodsComment;
}
public int getIsPhone() {
return isPhone;
}
public void setIsPhone(int isPhone) {
this.isPhone = isPhone;
}
public int getIsFavor() {
return isFavor;
}
public void setIsFavor(int isFavor) {
this.isFavor = isFavor;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
@Override
public InCart clone() {
return new InCart(goodsId, goodsName, goodsIcon, goodsType, goodsPrice, goodsPercent, goodsComment, isPhone, isFavor, num);
}
}
2、通过实体类进行操作数据库数据:
///通过Id查找数据----------(1)
InCart inCart = new Select().from(InCart.class)
.where("goodsId=?", mInCart.getGoodsId()).executeSingle();
if (inCart != null) {
// 若购物车中有,则数量+1
inCart.setNum(inCart.getNum() + 1);
//保存数据------------(2)
inCart.save();
} else {
mInCart.save();
}
3、广播通知其他界面更新UI的数据
(1)、购物车中:FragmentActivity
—->通过注册的广播标识来通知其他界面:
///仅仅只通知,不关闭她的本界面:
// 通知主页刷新购物车商品数
Intent intent = new Intent();
intent.setAction(Constants.BROADCAST_FILTER.FILTER_CODE);
intent.putExtra(Constants.BROADCAST_FILTER.EXTRA_CODE,
Constants.INTENT_KEY.REFRESH_INCART);
sendBroadcast(intent);
/跳转到购物车的界面并更新数据:
/**
* 跳转到首页购物车
*/
private void gotoHomePage() {
startActivity(new Intent(this, MainActivity.class));
Intent intent = new Intent();
intent.setAction(Constants.BROADCAST_FILTER.FILTER_CODE);
intent.putExtra(Constants.BROADCAST_FILTER.EXTRA_CODE,
Constants.INTENT_KEY.FROM_DETAIL);
sendBroadcast(intent);
finish();
overridePendingTransition(0, 0);
}
(2)、主页的广播注册:
// 注册广播接收者
receiver = new MyReceiver();
//broadcast_filter
IntentFilter filter = new IntentFilter(
Constants.BROADCAST_FILTER.FILTER_CODE);
registerReceiver(receiver, filter);
//广播:
class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String extra = intent
.getStringExtra(Constants.BROADCAST_FILTER.EXTRA_CODE);
if (extra.equals(Constants.INTENT_KEY.FROM_FAVOR)) {
isFromFavor = true;
}
/+++++初始化购物车显示数据空间
else if (extra.equals(Constants.INTENT_KEY.REFRESH_INCART)) {
initInCartNum();
}
}
}
具体的操作:
//1保存:
mInCart = new InCart("1", "避孕套", "", "成人用品", 23.00, "333dd", 1, 1, 1, 1);
mInCart.save();
//2修改:
String index = mInCart.getGoodsId();
InCart inCart = new Select().from(InCart.class).where("goodsId=?", index).executeSingle();
if (inCart != null) {
// 若购物车中有,则数量+1
inCart.setNum(inCart.getNum() + 1);
inCart.save();
settxt(inCart.getGoodsId(), inCart.getNum(), new Select().from(InCart.class).execute().size());
}
删除:
List<InCart> incart = new Select().from(InCart.class).execute();
Long iiii=incart.get(0).getId();
InCart item = InCart.load(InCart.class, iiii);
item.delete();
二、ToDoDB的数据实现:
public class ToDoDB extends SQLiteOpenHelper {
private final static String DATABASE_NAME = "yamadv_db";
private final static int DATABASE_VERSION = 3;
/*
* 新建购物车的信息表
*/
private final static String TABLE_NAME = "mycart_table";
public final static String FIELD_id = "_id";
public final static String cartType = "cart_Type";
public final static String taocanId = "tancan_Id";
public final static String cartCount = "cart_Count";
public final static String proId = "pro_Id";
public final static String prodimg = "prod_img";
public final static String prodname = "prod_name";
public final static String proddanjia = "prod_danjia";
public ToDoDB(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/*
* +++++++++++++++++++++++++++++++++++++++++++++++++++购物车的操作
*/
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE " + TABLE_NAME + " ("
+ FIELD_id + " INTEGER primary key autoincrement, "
+ proId + " INTEGER, "
+ cartType + " text, "
+ taocanId + " text, "
+ prodimg + " text, "
+ prodname + " text, "
+ proddanjia + " INTEGER, "
+ cartCount + " INTEGER)";
db.execSQL(sql);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "DROP TABLE IF EXISTS " + TABLE_NAME;
db.execSQL(sql);
onCreate(db);
}
public Cursor select() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db
.query(TABLE_NAME, null, null, null, null, null, null);
return cursor;
}
public long insert(int id, String types, String colors, int counts,
String proimg,String proname,int paodanjia) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(proId, id);
cv.put(cartType, types);
cv.put(taocanId, colors);
cv.put(cartCount, counts);
cv.put(prodimg, proimg);
cv.put(prodname, proname);
cv.put(proddanjia, paodanjia);
long row = db.insert(TABLE_NAME, null, cv);
return row;
}
public void delete(int id) {
SQLiteDatabase db = this.getWritableDatabase();
String where = FIELD_id + " = ?";
String[] whereValue = { Integer.toString(id) };
db.delete(TABLE_NAME, where, whereValue);
}
public void update(int id, int proid, String types, String colors,
int counts) {
SQLiteDatabase db = this.getWritableDatabase();
String where = FIELD_id + " = ?";
String[] whereValue = { Integer.toString(id) };
ContentValues cv = new ContentValues();
cv.put(proId, proid);
cv.put(cartType, types);
cv.put(taocanId, colors);
cv.put(cartCount, counts);
db.update(TABLE_NAME, cv, where, whereValue);
}
public void updatecount(int id, int counts) {
SQLiteDatabase db = this.getWritableDatabase();
String where = FIELD_id + " = ?";
String[] whereValue = { Integer.toString(id) };
ContentValues cv = new ContentValues();
cv.put(cartCount, counts);
db.update(TABLE_NAME, cv, where, whereValue);
}
}
相关操作:
(1)、查询:
myToDoDB = new ToDoDB(BadyDetilActivity.this);
/* 取得DataBase里的数据 */
myCursor = myToDoDB.select();
从查询的table中获取一条数据:
/* 将myCursor移到所点击的值 */
myCursor.moveToPosition(0);
/* 取得字段_id的值 */
int _id = myCursor.getInt(0);
(2)、新增:
// ++++++++++++++++++++++++++++++++新增操作
private void addTodo(int id, String types, String cantanID, int counts, String img, String pname, int danjia) {
/* 添加数据到数据库 */
myToDoDB.insert(id, types, cantanID, counts, img, pname, danjia);
/* 重新查询 */
myCursor.requery();
}
三、xutils的dbxuils的使用:
需要的权限
<uses-permissionandroid:name="android.permission.INTERNET"/>
<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
创建数据库
DaoConfig config = new DaoConfig(context);
config.setDbName("xUtils-demo"); //db名
config.setDbVersion(1); //db版本
DbUtils db = DbUtils.create(config);//db还有其他的一些构造方法,比如含有更新表版本的监听器的
创建表
db.createTableIfNotExist(User.class); //创建一个表User
db.save(user);//在表中保存一个user对象。最初执行保存动作时,也会创建User表
删除表
db.dropTable(User.class);
开启事务
db.configAllowTransaction(true);
db相关Annotation
@Check check约束
@Column 列名
@Finder 一对多、多对一、多对多关系(见sample的Parent、Child中的使用)
@Foreign 外键
@Id 主键,当为int类型时,默认自增。 非自增时,需要设置id的值
@NoAutoIncrement 不自增
@NotNull 不为空
@Table 表名
@Transient 不写入数据库表结构
@Unique 唯一约束
//相关常用法:
DbUtils db = DbUtils.create(this);
User user = new User(); //这里需要注意的是User对象必须有id属性,或者有通过@ID注解的属性
user.setEmail("wyouflf@qq.com");
user.setName("wyouflf");
db.save(user); // 使用saveBindingId保存实体时会为实体的id赋值
...
// 查找
Parent entity = db.findById(Parent.class, parent.getId());
List<Parent> list = db.findAll(Parent.class);//通过类型查找
Parent Parent = db.findFirst(Selector.from(Parent.class).where("name","=","test"));
// IS NULL
Parent Parent = db.findFirst(Selector.from(Parent.class).where("name","=", null));
// IS NOT NULL
Parent Parent = db.findFirst(Selector.from(Parent.class).where("name","!=", null));
// WHERE id<54 AND (age>20 OR age<30) ORDER BY id LIMIT pageSize OFFSET pageOffset
List<Parent> list = db.findAll(Selector.from(Parent.class)
.where("id" ,"<", 54)
.and(WhereBuilder.b("age", ">", 20).or("age", " < ", 30))
.orderBy("id")
.limit(pageSize)
.offset(pageSize * pageIndex));
// op为"in"时,最后一个参数必须是数组或Iterable的实现类(例如List等)
Parent test = db.findFirst(Selector.from(Parent.class).where("id", "in", new int[]{1, 2, 3}));
// op为"between"时,最后一个参数必须是数组或Iterable的实现类(例如List等)
Parent test = db.findFirst(Selector.from(Parent.class).where("id", "between", new String[]{"1", "5"}));
DbModel dbModel = db.findDbModelAll(Selector.from(Parent.class).select("name"));//select("name")只取出name列
List<DbModel> dbModels = db.findDbModelAll(Selector.from(Parent.class).groupBy("name").select("name", "count(name)"));
...
//例:分组聚合查询出 Parent表中 非重复的name和它的对应数量
List<DbModel> dbModels = db.findDbModelAll(Selector.form(Parent.class).select("distinct name,count(name) as num").groupBy("name"));
db.execNonQuery("sql") // 执行自定义sql
...