Gradle:
compile 'com.github.satyan:sugar:1.3'It requires minimal configuration.
All you need to do is, specify SugarApp as your application class in AndroidManifest.xml. You do that by changing the android:name attribute of the application tag.
<application android:label="@string/app_name" android:icon="@drawable/icon"
android:name="com.orm.SugarApp">
.
.
<meta-data android:name="DATABASE" android:value="sugar_example.db" />
<meta-data android:name="VERSION" android:value="2" />
<meta-data android:name="QUERY_LOG" android:value="true" />
<meta-data android:name="DOMAIN_PACKAGE_NAME" android:value="com.example" />
.
.
</application>The meta-data tags are all optional and serve the following purpose:
| Metadata | Description |
|---|---|
DATABASE
|
Name of the generated sqlite database file. eg: app_name.db |
VERSION
|
Version of your database schema. |
QUERY_LOG
|
Logs the generated Select queries. |
DOMAIN_PACKAGE_NAME
|
Specify a package name where your domain/entity classes are present. This helps in smoother table creation. |
Extend SugarRecord for all the classes that you need persisted. That's it. Sugar takes care of table creation for you.
Note: Please retain the default constructor.
public class Book extends SugarRecord<Book> {
String title;
String edition;
public Book(){
}
public Book(String title, String edition){
this.title = title;
this.edition = edition;
}
}Performing CRUD operations are very simple. Functions like save(), delete() and findById(..) are provided to make the work easy.
Note: Record indexes start at index 1.
Book book = new Book(ctx, "Title here", "2nd edition")
book.save();Book book = Book.findById(Book.class, 1);Book book = Book.findById(Book.class, 1);
book.title = "updated title here"; // modify the values
book.edition = "3rd edition";
book.save(); // updates the previous entry with new values.Book book = Book.findById(Book.class, 1);
book.delete();List<Book> books = Book.listAll(Book.class);
Book.deleteAll(Book.class);