安卓数据库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("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
...
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android Room是Google为Android平台开发的一个SQLite对象映射数据库框架,它提供了一种简单的方式来访问SQLite数据库。下面是使用Room进行SQLite查询的基本步骤: 1. 定义实体类:在Room中,表是通过实体类来表示的。你需要定义一个Java类来表示数据库中的每个表,并使用注释来指定表名、列名等信息。 2. 定义DAO接口:DAO(Data Access Object)是用于访问数据库的接口。你需要定义一个接口来提供对实体类的CRUD操作。 3. 创建数据库:使用Room,你可以在应用程序中创建一个SQLite数据库。你需要创建一个继承自RoomDatabase的抽象类,并定义抽象方法来获取DAO对象。 4. 执行查询操作:在DAO接口中定义查询语句,并在应用程序中调用该方法来执行查询操作。以下是一个使用Room进行查询的示例: ```java @Dao public interface UserDao { @Query("SELECT * FROM user WHERE id = :userId") User getUserById(int userId); @Query("SELECT * FROM user WHERE name LIKE :name") List<User> getUsersByName(String name); @Insert void insertUser(User user); } ``` 在上面的示例中,@Query注释指定了查询语句,getUserById方法根据用户ID查询用户,getUsersByName方法根据名称查询用户,insertUser方法将用户插入数据库。 要使用上述查询方法,你需要创建一个RoomDatabase实例并获取UserDao对象。以下是一个使用Room进行查询的示例: ```java UserDatabase db = Room.databaseBuilder(getApplicationContext(), UserDatabase.class, "user.db").build(); UserDao userDao = db.userDao(); // 根据ID查询用户 User user = userDao.getUserById(1); // 根据名称查询用户 List<User> users = userDao.getUsersByName("John"); // 插入用户 User newUser = new User("Alice", "[email protected]"); userDao.insertUser(newUser); ``` 在上面的示例中,我们创建了一个UserDatabase实例,并使用其userDao()方法获得UserDao对象。然后我们可以使用UserDao对象的方法来执行查询和插入操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值