ActiveAndroid的使用

ActiveAndroid是采用活动记录(Active Record)架构模式设计的适用于Android平台的轻量级ORM架构。


项目主页:https://github.com/pardom/ActiveAndroid


1.配置与初始化

首先在AndroidManifest.xml文件中配置数据库名称和数据库版本号。

<manifest ...>
    <application android:name="com.activeandroid.app.Application" ...>
 
        ...
 
        <meta-data android:name="AA_DB_NAME" android:value="数据库名字.db" />
        <meta-data android:name="AA_DB_VERSION" android:value="数据库版本号" />
    </application>
</manifest>

  • AA_DB_NAME:数据库名

  • AA_DB_VERSION:数据库版本号,默认是1。

接着,在AndroidManifest.xml文件中指定application元素的name为 com.activeandroid.app.Application,如果需要自定义Application,需要让你的Application对象继 承自com.activeandroid.app.Application而不是android.app.Application。如果你需要继承其他库 的Application,则需要在Application中初始化和处理ActiveAndroid。

public class MyApplication extends SomeLibraryApplication {
    @Override
    public void onCreate() {
        super.onCreate();
        ActiveAndroid.initialize(this);
    }
    @Override
    public void onTerminate() {
        super.onTerminate();
        ActiveAndroid.dispose();
    }
}



2.创建Model

创建数据库模型非常简单,创建的模型必须继承Model类,这样你的类名就是你的表名。如果不想使用类名做表名,则可以使用@Table定义表名。@Column用于定义列名。Model类使用无参的构造函数,如果定义自己的构造函数必须定义一个无参的构造函数。

@Table(name = "Categories")
public class Category extends Model {
    @Column(name = "Name")
    public String name;
}
 
@Table(name = "Items")
public class Item extends Model {
    @Column(name = "remote_id", unique = true, onUniqueConflict = Column.ConflictAction.REPLACE)
    public int remoteId;
    @Column(name = "Name")
    public String name;
 
    @Column(name = "Category")
    public Category category;
 
        public Item(){
                super();
        }
        public Item(String name, Category category){
                super();
                this.name = name;
                this.category = category;
        }
}



3.增删改查


3.1 插入

3.1.1 单条插入

保存一条记录,只需要创建一个模型的实例,并为每个字段指定值,然后调用save()方法。

Category restaurants = new Category();
restaurants.name = "Restaurants";
restaurants.save();

3.1.2批量插入

ActiveAndroid.beginTransaction();
try {
        for (int i = 0; i < 100; i++) {
            Item item = new Item();
            item.name = "Example " + i;
            item.save();
        }
        ActiveAndroid.setTransactionSuccessful();
}
finally {
        ActiveAndroid.endTransaction();
}

3.2 更新

new Update(Person.class).set("age=?," + "name=?", age, name).execute();


3.3 删除

调用delete()方法就可以删除一条记录,下面的例子中,通过id加载一个Item对象,并且删除他。

Item item = Item.load(Item.class, 1);
item.delete();
也可以通过静态方法删除

Item.delete(Item.class, 1);

也可以创建调用Delete对象删除

new Delete().from(Item.class).where("Id = ?", 1).execute();

3.4 查询

查询一条

public static Item getRandom(Category category) {
    return new Select()
        .from(Item.class)
        .where("Category = ?", category.getId())
        .orderBy("RANDOM()")
        .executeSingle();
}
查询所有
public static List<Item> getAll(Category category) {
    return new Select()
        .from(Item.class)
        .where("Category = ?", category.getId())
        .orderBy("Name ASC")
        .execute();
}


4. 使用内容提供者

使用ActiveAndroid的ContentProvider,必须复写默认的标识列如下所示(默认标识列是ID)。

@Table(name = "Items", id = BaseColumns._ID)
public class Item extends Model {...}
接着就可以使用 ContentProvider
mySpinner.setAdapter(new SimpleCursorAdapter(getActivity(),
        android.R.layout.simple_expandable_list_item_1,
        null,
        new String[] { "MyProperty" },
        new int[] { android.R.id.text1 },
        0));
 
    getActivity().getSupportLoaderManager().initLoader(0, null, new LoaderCallbacks<Cursor>() {
        @Override
        public Loader<Cursor> onCreateLoader(int arg0, Bundle cursor) {
            return new CursorLoader(getActivity(),
                ContentProvider.createUri(MyEntityClass.class, null),
                null, null, null, null
            );
        }
 
        @Override
        public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
            ((SimpleCursorAdapter)mySpinner.getAdapter()).swapCursor(cursor);
        }
 
        @Override
        public void onLoaderReset(Loader<Cursor> arg0) {
            ((SimpleCursorAdapter)mySpinner.getAdapter()).swapCursor(null);
        }
    });

最后别忘了在 AndroidManifest.xml 中注册 provider
<application ...>
    <provider android:authorities="com.example" android:exported="false" android:name="com.activeandroid.content.ContentProvider" />
    ...
</application>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值