安卓數據庫activeandroid框架

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("[email protected]");
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
...
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章