1.在清单配置文件中做如下配置:
AA_DB_NAME (数据库名称,这个name不能改,但是是可选的,如果不写的话 是默认的"Application.db"这个值)
AA_DB_VERSION (数据库版本号,同样是可选的 – 默认为1)
<manifest ...>
<application android:name="com.activeandroid.app.Application" ...>...
<meta-data android:name="AA_DB_NAME" android:value="Pickrand.db" />
<meta-data android:name="AA_DB_VERSION" android:value="5" />
</application>
</manifest>
2.创建AppContext继承于com.activeandroid.app.Application:
这个<application>是必须指定的,但你也可以使用自己的Application,继承自com.activeandroid.app.Application
public class MyApplication extends com.activeandroid.app.Application { ...
如果你不想或者不能继承com.activeandroid.app.Application的话,那么就这样
public class MyApplication extends SomeLibraryApplication {
@Override
public void onCreate() {
super.onCreate();
ActiveAndroid.initialize(this);
}
@Override
public void onTerminate() {
super.onTerminate();
ActiveAndroid.dispose();
}
}
ActiveAndroid.initialize(this);做初始化工作,ActiveAndroid.dispose();做清理工作
3.创建数据库继承于Model
我们使用@Table(name = "Items")来表示表,使用@Column(name = "Name")来表示列,ActiveAndroid会使用自增长的ID作为主键,然后按照注解描述,将类对应映射为数据库表。
@Table(name = "Categories")
public class Category extends Model {
@Column(name = "Name")
public String name;
}
@Table(name = "Items")
public class Item extends Model {
@Column(name = "Name")
public String name;
@Column(name = "Category")
public Category category;
}
4.增删改查
删除的三种方式:
Item item = Item.load(Item.class, 1);
item.delete();
Item.delete(Item.class, 1);
new Delete().from(Item.class).where("Id = ?", 1).execute();
代码如下:
public void insert(View view) {
User user = new User();
user.setName("代粮鲜:"+System.currentTimeMillis());
user.setAge("22");
user.setSex("不知道");
user.save();
}
public void delete(View view) {
//
Delete delete = new Delete();
delete.from(User.class).where("id = ?",14).execute();
//executeSingle 查询一条记录
Select select = new Select();
User user = select.from(User.class).where("id = 12").executeSingle();
if (user != null) {
user.delete();
}
}
public void query(View view) {
Select select = new Select();
//executeSingle 查询一条记录
User user = select.from(User.class).executeSingle();
Log.e(TAG,"user:"+user.toString());
//查询 一组数据
List<User> users = select.from(User.class).execute();
for (User u : users) {
Log.e(TAG,"users:"+u.toString());
}
// User userAsc = select.from(User.class).orderBy("id ASC").executeSingle();
// User userDESC = select.from(User.class).orderBy("id DESC").executeSingle();
// select.from(User.class).where("id = ? or id = ?","5","6").limit(10).offset(10).execute();
List<User> users2 = select.from(User.class).where("id = ?","5").or("id like ?","%1%").limit(10).execute();
// List<User> users2 = select.from(User.class).where("id = ?", "5").and("id = ?", "10").limit(10).offset(10).execute();
for (User u : users2) {
Log.e(TAG,"users2:"+u.toString());
}
}
public void update(View view) {
// user.save(); 如果存在 更新 不存在 添加
}
优点:不在受限于内部类不能创建表的情况;
自动选择自增长的id作为主键,不会出现键值不唯一的情况;
操作简便;