Skip to content

Tutorial

Alessandro Svetina edited this page Apr 16, 2018 · 14 revisions

In this tutorial it will be show how easy is use Kripton Persistence Library to retrieve JSON data retrieved from REST service and manage it in a SQLite database. You can download the Android Studio full project from KriptonQuickStart.

A compiled version of App showed in this tutorial is available though Google play store

qr code

Get it on Google Play

The REST service used in this tutorial is hosted by jsonplaceholder.

So let's start. We have the following domain model:

system model

First of all, we define class model:

Address.java

@BindType
public class Address {
    public String street;
    public String suite;
    public String city;
    public String zipcode;
    public Geo geo;
}

Comment.java

@BindType
public class Comment {
    public long postId;
    public long id;
    public String name;
    public String email;
    public String body;
}

Company.java

@BindType
public class Company {
    public String name;
    public String catchPhrase;
    public String bs;
}

Geo.java

@BindType
public class Geo {
    public String lat;
    public String lng;
}

Post.java

@BindType
public class Post {
    public long userId;
    public long id;
    public String title;
    public String body;
}

Todo.java

@BindType
public class Todo {
    public long id;
    public long userId;
    public String title;
    public boolean completed;
}

User.java

@BindType
public class User {
    public long id;
    public String name;
    public String username;
    public String email;
    public Address address;
    public String phone;
    public String website;
    public Company company;
}

Now define interface to consume REST service with Retrofit:

QuickStartService.java

public interface QuickStartService {
	
	@GET("posts")
	Call<List<Post>> listPosts(@Query("userId") long userId);

	@GET("todos")
	Call<List<Todo>> listTodos(@Query("userId") long userId);

	@GET("comments")
	Call<List<Comment>> listComments(@Query("postId") long postId);

	@GET("albums")
	Call<List<Album>> listAlbums(@Query("userId") long userId);

	@GET("photos")
	Call<List<Photo>> listPhotos(@Query("albumId") long albumId);

	@GET("users")
	Call<List<User>> listUsers();
}

The integration between Retrofit and Kripton can be done with the following lines of code

Retrofit retrofit = new Retrofit.Builder()
  .baseUrl("https://jsonplaceholder.typicode.com/")
  .addConverterFactory(KriptonBinderConverterFactory.create())
  .build();

service = retrofit.create(QuickStartService.class);

Next step is define SQLite persistence interface. To bind model class to SQLite, just define interface for SQLite datasource:

QuickStartDataSource.java

@BindDataSource(daoSet={UserDao.class, PostDao.class, CommentDao.class, TodoDao.class, 
     AlbumDao.class, PhotoDao.class}, fileName = "kripton.quickstart.db")
public interface QuickStartDataSource {
}

And the DAO's interface for the managed entities:

AlbumDao.java

@BindDao(Album.class)
public interface AlbumDao {
    @BindSqlInsert(includePrimaryKey = true)
    void insert(Album bean);

    @BindSqlSelect(where="userId = ${value}")
    List<Album> selectByUserId(@BindSqlParam("value") long userId);

    @BindSqlSelect(where="id = ${value}")
    Album selectOneByUserId(@BindSqlParam("value") long userId);

}

CommentDao.java

@BindDao(Comment.class)
public interface CommentDao {
    @BindSqlInsert(includePrimaryKey = true)
    void insert(Comment bean);

    @BindSqlSelect(where="postId = ${value}")
    List<Comment> selectByPostId(@BindSqlParam("value") long postId);

    @BindSqlSelect(where="id = ${value}")
    Comment selectOneByPostId(@BindSqlParam("value") long postId);

}

PhotoDao.java

@BindDao(Photo.class)
public interface PhotoDao {
    @BindSqlInsert(includePrimaryKey = true)
    void insert(Photo bean);

    @BindSqlSelect(where="albumId = ${value}")
    List<Photo> selectByUserId(@BindSqlParam("value") long albumId);

    @BindSqlSelect(where="id = ${value}")
    Photo selectOneByUserId(@BindSqlParam("value") long albumId);

}

PostDao.java

@BindDao(Post.class)
public interface PostDao {
    @BindSqlInsert(includePrimaryKey = true)
    void insert(Post bean);

    @BindSqlSelect(where="userId = ${value}")
    List<Post> selectByUserId(@BindSqlParam("value") long userId);

    @BindSqlSelect(where="id = ${value}")
    Post selectOneByUserId(@BindSqlParam("value") long userId);

}

TodoDao.java

@BindDao(Todo.class)
public interface TodoDao {
    @BindSqlInsert(includePrimaryKey = true)
    void insert(Todo bean);

    @BindSqlSelect(where="userId = ${value}")
    List<Todo> selectByUserId(@BindSqlParam("value") long userId);

    @BindSqlSelect(where="id = ${value}")
    Todo selectOneByUserId(@BindSqlParam("value") long userId);

}

UserDao.java

@BindDao(User.class)
public interface UserDao {

    @BindSqlInsert(includePrimaryKey = true)
    void insert(User bean);

    @BindSqlSelect(orderBy = "username asc")
    List<User> selectAll();

    @BindSqlSelect(where="id = ${value}")
    User selectById(@BindSqlParam("value") long id);

}

These interfaces allow to generate the following database schema:

database_schema

Foreach DAO interface definition will be generated a DAO implementation. UserDao will be associated to UserDaoImpl class, TodoDao interface to TodoDaoImpl class and so on. Every DAO will be avaiable throw data source interface implementation that Kripton will generate.

That's it. During compilation, Kripton will generate:

  • Necessary code for JSON/XML persistence management of bean marked with @BindType annotation
  • Necessary code for SQLite database management, associated DAO's, transaction management and specialized cursor for each DAO (optional)
  • AsyncTask class to execute asycn operation with datasource (optional)

Just for example, the following code retrieve user list from SQLite:

// SQLite instance's name wil be 'Bind<Data_source_name>'
BindQuickStartDataSource dataSource=BindQuickStartDataSource.instance();
dataSource.openDatabase(); // open database
// execute SELECT id, name, username, email, address, phone, website, company FROM user WHERE 1=1 ORDER BY username asc
UserDaoImpl dao=dataSource.getUserDao();
List<User> userList=dao.selectAll(); 
// close database
dataSource.close(); 

Moreover, all database operation is logged on logcat (you can disable it), so when application start, you will see in you log about DDL (text is indented for readability):

CREATE TABLE user (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  name TEXT, 
  username TEXT, 
  email TEXT, 
  address BLOB, 
  phone TEXT, 
  website TEXT, 
  company BLOB
);

CREATE TABLE todo (
  id INTEGER PRIMARY KEY AUTOINCREMENT, 
  user_id INTEGER, 
  title TEXT, 
  completed INTEGER, 
  FOREIGN KEY(user_id) REFERENCES user(id)
);

CREATE TABLE post (
  user_id INTEGER, 
  id INTEGER PRIMARY KEY AUTOINCREMENT, 
  title TEXT, 
  body TEXT, 
  FOREIGN KEY(user_id) REFERENCES user(id)
);

CREATE TABLE comment (
  post_id INTEGER, 
  id INTEGER PRIMARY KEY AUTOINCREMENT, 
  name TEXT, 
  email TEXT, 
  body TEXT, 
  FOREIGN KEY(post_id) REFERENCES post(id)
);

CREATE TABLE album (
  user_id INTEGER, 
  id INTEGER PRIMARY KEY AUTOINCREMENT, 
  title TEXT, 
  FOREIGN KEY(user_id) REFERENCES user(id)
);

CREATE TABLE photo (
  album_id INTEGER, 
  id INTEGER PRIMARY KEY AUTOINCREMENT, 
  title TEXT, 
  url TEXT, 
  thumbnail_url TEXT, 
  FOREIGN KEY(album_id) REFERENCES album(id)
);

And log about SQL execution:

SELECT id, name, username, email, address, phone, website, company FROM user WHERE 1=1 ORDER BY username asc

or (text is indented for readability)

INSERT INTO user 
  (id, name, username, email, address, phone, website, company) 
  VALUES 
  ('1', 'Leanne Graham', 'Bret', 'Sincere@april.biz', 
   '{"city":"Gwenborough","geo":{"lat":"-37.3159","lng":"81.1496"...', '1-770-736-8031 x56442', 'hildegard.org',
   '{"bs":"harness real-time e-markets","catchPhrase":"Multi-laye...'
  )

Table of Contents

Query definition

Features

Relations

Multithread supports

Modularization

Annotations for data convertion

Annotations for SQLite ORM

Annotations for shared preferences

Clone this wiki locally