Monday, 4 May 2015

HB Blog 71: Active Android - ORM (Object Relational Mapper).

Object-relational mapping is a programming technique for converting data between incompatible type systems in object-oriented programming languages. ActiveAndroid is an active record style ORM (object relational mapper). ActiveAndroid allows you to save and retrieve SQLite database records without ever writing a single SQL statement. Each database record is wrapped neatly into a class with methods like save() and delete().

There are few below steps to follow for using ActiveAndroid :-
1)Add ActiveAndroid library to your project. If you're using Android Studio, drag the jar to the libs folder of project and select "Add as a Library…".
2)Modify your build.gradle as below,
1
2
3
4
5
6
repositories {
    mavenCentral()
    maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
}

compile 'com.michaelpardo:activeandroid:3.1.0-SNAPSHOT'

3)Update Android Manifest file of your project for global setting as below,
1
2
3
4
5
6
7
8
<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>

4)Just extend com.activeandroid.app.Application instead of android.app.Application or initialise using ActiveAndroid.initialize(this); in the Application class.
5)Finally the setup is completed and now you can now create the database model, create classes named your desired table name, which have annotated fields for each of the columns. Your class must extend the Model class and your members must be annotated using @Column. ActiveAndroid will handle primitive data types as well as relationships to other tables and date classes. ActiveAndroid creates an id field for your tables. This field is an auto-incrementing primary key.

Here is a sample example,
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
@Table(name = "Items")
public class Item extends Model {
        // If name is omitted, then the field name is used.
        @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;
        }
}

No comments:

Post a Comment