• Stars
    star
    122
  • Rank 292,031 (Top 6 %)
  • Language
    Java
  • License
    Apache License 2.0
  • Created over 6 years ago
  • Updated over 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A simple notes app to demo Room + LiveData implementation in Android

RoomDb-Sample

This is a demo app on how to implement Room persistance library, making use of LiveData in Android app



How to implement Room: a SQLite object mapping library in your Android app?

Step 1: Add following library and annotation processor to your app gradle file.
compile "android.arch.persistence.room:runtime:1.0.0"
annotationProcessor "android.arch.persistence.room:compiler:1.0.0" 

Note: The reason why annotation processor is needed is because all operations like Insert, Delete, Update etc are annotated.

Step 2: Component 1 in room - Create an entity class:
This is nothing but a model class annotated with @Entity where all the variable will becomes column name for the table and name of the model class becomes name of the table. The name of the class is the table name and the variables are the columns of the table
Example: Note.java

@Entity
public class Note implements Serializable {

    @PrimaryKey(autoGenerate = true)
    private int id;

    private String title;
    private String description;


    @ColumnInfo(name = "created_at")
    @TypeConverters({TimestampConverter.class})
    private Date createdAt;

    @ColumnInfo(name = "modified_at")
    @TypeConverters({TimestampConverter.class})
    private Date modifiedAt;

    private boolean encrypt;
    private String password;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Date getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(Date createdAt) {
        this.createdAt = createdAt;
    }

    public Date getModifiedAt() {
        return modifiedAt;
    }

    public void setModifiedAt(Date modifiedAt) {
        this.modifiedAt = modifiedAt;
    }

    public boolean isEncrypt() {
        return encrypt;
    }

    public void setEncrypt(boolean encrypt) {
        this.encrypt = encrypt;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

Step 3: Component 2 in room - Create a DAO class
This is an interface which acts is an intermediary between the user and the database. All the operation to be performed on a table has to be defined here. We define the list of operation that we would like to perform on table
Example: DaoAccess.java

@Dao
public interface DaoAccess {

    @Insert
    Long insertTask(Note note);


    @Query("SELECT * FROM Note ORDER BY created_at desc")
    LiveData<List<Note>> fetchAllTasks();


    @Query("SELECT * FROM Note WHERE id =:taskId")
    LiveData<Note> getTask(int taskId);


    @Update
    void updateTask(Note note);


    @Delete
    void deleteTask(Note note);
}

Step 4: Component 3 in room - Create Database class
This is an abstract class where you define all the entities that means all the tables that you want to create for that database. We define the list of operation that we would like to perform on table
Example: NoteDatabase.java

@Database(entities = {Note.class}, version = 1, exportSchema = false)
public abstract class NoteDatabase extends RoomDatabase {

    public abstract DaoAccess daoAccess();
}

Step 5: Create the Repository class
A Repository mediates between the domain and data mapping layers, acting like an in-memory domain object collection. We access the database class and the DAO class from the repository and perform list of operations such as insert, update, delete, get
Example: NoteRepository.java

public class NoteRepository {

    private String DB_NAME = "db_task";

    private NoteDatabase noteDatabase;
    public NoteRepository(Context context) {
        noteDatabase = Room.databaseBuilder(context, NoteDatabase.class, DB_NAME).build();
    }

    public void insertTask(String title,
                           String description) {

        insertTask(title, description, false, null);
    }

    public void insertTask(String title,
                           String description,
                           boolean encrypt,
                           String password) {

        Note note = new Note();
        note.setTitle(title);
        note.setDescription(description);
        note.setCreatedAt(AppUtils.getCurrentDateTime());
        note.setModifiedAt(AppUtils.getCurrentDateTime());
        note.setEncrypt(encrypt);


        if(encrypt) {
            note.setPassword(AppUtils.generateHash(password));
        } else note.setPassword(null);

        insertTask(note);
    }

    public void insertTask(final Note note) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... voids) {
                noteDatabase.daoAccess().insertTask(note);
                return null;
            }
        }.execute();
    }

    public void updateTask(final Note note) {
        note.setModifiedAt(AppUtils.getCurrentDateTime());

        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... voids) {
                noteDatabase.daoAccess().updateTask(note);
                return null;
            }
        }.execute();
    }

    public void deleteTask(final int id) {
        final LiveData<Note> task = getTask(id);
        if(task != null) {
            new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... voids) {
                    noteDatabase.daoAccess().deleteTask(task.getValue());
                    return null;
                }
            }.execute();
        }
    }

    public void deleteTask(final Note note) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... voids) {
                noteDatabase.daoAccess().deleteTask(note);
                return null;
            }
        }.execute();
    }

    public LiveData<Note> getTask(int id) {
        return noteDatabase.daoAccess().getTask(id);
    }

    public LiveData<List<Note>> getTasks() {
        return noteDatabase.daoAccess().fetchAllTasks();
    }
}

Note: DO NOT PERFORM OPERATION ON MAIN THREAD AS APP WILL CRASH


Sample Implementation of basic CRUD operations using ROOM
1. Insert:

   NoteRepository noteRepository = new NoteRepository(getApplicationContext());
   String title = "This is the title of the third task";
   String description = "This is the description of the third task";
   noteRepository.insertTask(title, description);

2. Update:

   NoteRepository noteRepository = new NoteRepository(getApplicationContext());
   Note note = noteRepository.getTask(2);
   note.setEncrypt(true);
   note.setPassword(AppUtils.generateHash("Password@1"));
   note.setTitle("This is an example of modify");
   note.setDescription("This is an example to modify the second task");

   noteRepository.updateTask(note);

3. Delete:

   NoteRepository noteRepository = new NoteRepository(getApplicationContext());
   noteRepository.deleteTask(3);

4. Get all notes:

   NoteRepository noteRepository = new NoteRepository(getApplicationContext());

   noteRepository.getTasks().observe(appContext, new Observer<List<Note>>() {
       @Override
       public void onChanged(@Nullable List<Note> notes) {
           for(Note note : notes) {
               System.out.println("-----------------------");
               System.out.println(note.getId());
               System.out.println(note.getTitle());
               System.out.println(note.getDescription());
               System.out.println(note.getCreatedAt());
               System.out.println(note.getModifiedAt());
               System.out.println(note.getPassword());
               System.out.println(note.isEncrypt());
            }
        }
    });

5. Get single note by id:

   NoteRepository noteRepository = new NoteRepository(getApplicationContext());
   Note note = noteRepository.getTask(2);

And that's it! It's super simple. You can check out the official documentation here

More Repositories

1

Android-Cheat-sheet

Cheat Sheet for Android Interviews
Java
2,162
star
2

Biometric-Auth-Sample

Add Biometric Authentication to any Android app
Java
246
star
3

DeviceInfo-Sample

[Android Library] Get easy access to device information super fast, real quick
Kotlin
204
star
4

TrailersApp

A simple demo project for The Movie DB based on MVVM clean architecture.
Java
197
star
5

PagingLibrary-Sample

An open source app that is refactored to demo Paging Library from Android Jetpack
Java
170
star
6

Today-I-Learned

A collection of small things I learn day to day across a variety of languages and technologies
155
star
7

Wifi-Connect

A library project to connect two devices using Wifi-Direct
Java
105
star
8

ConstraintLayout-Sample

A demo app to showcase constraint layout implementation in Android
Java
105
star
9

OnboardingSample

Beginners - A demo of an onboarding screen in iOS using Swift
Swift
97
star
10

Dagger2-Sample

A sample app to demo how to implement dagger in Android using Dagger Android Support library
Java
77
star
11

Github-Trending-Repos

An Android App that lists the most trending repositories from Github.
Java
60
star
12

RxAndroid-Sample

A list of concise write ups on the implementation of RxJava in Android
Java
36
star
13

Optimize

Android library for displaying data based on JSON configuration fetched from server. With this library, you can kiss goodbye to string.xml, dimen.xml, arrays.xml. Keep all your string/integer/array config in one file. The library will automatically fetch the data from the url you provide.
Java
35
star
14

CustomFontView

Custom View classes for TextView, EditText & Buttons - to set custom fonts
Java
27
star
15

Inshorts

A demo app news app for a hackathon - includes MVP architecture example
Java
23
star
16

RxNetworkEvent-Example

This is a sample app to demonstrate error handling using Retrofit2 and RxJava2
Java
22
star
17

AESEncryption

A demo of how to implement AES encryption in Android & iOS
Swift
21
star
18

Trailers

An open source app that is refactored to demo MVVM architecture
Java
20
star
19

otpview

A simple custom view class to enter otp
Java
19
star
20

GameOfThronesTrivia

An open source app that is refactored to demo ViewModel and LiveData
Java
17
star
21

DataBindingExample

A demo of how to implement Data Binding in Android app
Java
11
star
22

Jni-Sample

A simple project that demonstrates the use of jni to communicate between native and Java code in Android
Java
10
star
23

Ussd-app

A POC app for USSD implementation in Android
Java
6
star
24

RequestTask

Android library wrapper for HttpUrlConnection
Java
5
star
25

Github-Repo-Sample

A demo app that follows clean architecture which includes:
Kotlin
3
star
26

VDOPlayer

A simple video player app
Java
2
star