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

Overview

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

You might also like...
Android common lib demo, include ImageCache, HttpCache, DropDownListView, DownloadManager, install apk silent and so on, you can find description
Android common lib demo, include ImageCache, HttpCache, DropDownListView, DownloadManager, install apk silent and so on, you can find description

android-demo 关于我,欢迎关注 微博:Trinea 主页:trinea.cn 邮箱:trinea.cn#gmail.com 微信:codek2 依赖:trinea-android-common android-auto-scroll-view-pager viewpager-indica

Restaurant is a demo application based on modern Android application tech-stacks and MVVM architecture
Restaurant is a demo application based on modern Android application tech-stacks and MVVM architecture

Restaurant is a demo application based on modern Android application tech-stacks and MVVM architecture. Fetching data from the network via repository pattern.

Demo Android application using Gradle. Project is written entirely in Kotlin with MVVM architecture
Demo Android application using Gradle. Project is written entirely in Kotlin with MVVM architecture

Demo Android application using Gradle. Project is written entirely in Kotlin with MVVM architecture, Dagger / Hilt Dependency Injection, Room Database and Retrofit API Calls

A demo of the power menu with Reveal and other animations
A demo of the power menu with Reveal and other animations

MaterialPowerMenu A demo of the power menu with Reveal and other animations Some days ago, I saw a gif on Google+ demonstating a concept of Android Po

A simple app to showcase Androids Material Design and some of the cool new cool stuff in Android Lollipop. RecyclerView, CardView, ActionBarDrawerToggle, DrawerLayout, Animations, Android Compat Design, Toolbar
A simple app to showcase Androids Material Design and some of the cool new cool stuff in Android Lollipop. RecyclerView, CardView, ActionBarDrawerToggle, DrawerLayout, Animations, Android Compat Design, Toolbar

#Android-LollipopShowcase This is a simple showcase to show off Android's all new Material Design and some other cool new stuff which is (new) in Andr

A simple app to showcase Androids Material Design and some of the cool new cool stuff in Android Lollipop. RecyclerView, CardView, ActionBarDrawerToggle, DrawerLayout, Animations, Android Compat Design, Toolbar
A simple app to showcase Androids Material Design and some of the cool new cool stuff in Android Lollipop. RecyclerView, CardView, ActionBarDrawerToggle, DrawerLayout, Animations, Android Compat Design, Toolbar

#Android-LollipopShowcase This is a simple showcase to show off Android's all new Material Design and some other cool new stuff which is (new) in Andr

simple android grocery app using kotlin and android studio
simple android grocery app using kotlin and android studio

Project Idea The idea of this project is to make a grocery android app that users can use to order the groceries they want. It doesn't contain any bac

🔥 Android MVP with Volley usage simple registration App 🔥

🔥 Android MVP with Volley usage simple registration App 🔥 This is a MVP architecture app that uses volley .Project is made using Android Studio. Vol

This repository provides a simple clicker app using `KSharedDataStorage` to save progress

kds-android-example This repository provides a simple clicker app using KSharedDataStorage to save progress For progress saving used KSharedDataStorag

Comments
  • An error found while back to home page after a note saved

    An error found while back to home page after a note saved

    We first thanks for create this awesome working demo with newest android arch component room.

    after i forked the git and run the application in android 8.1 orio; i found an error .

    09-20 17:12:49.027 9717-9830/com.an.room E/AndroidRuntime: FATAL EXCEPTION: pool-1-thread-2 Process: com.an.room, PID: 9717 java.lang.ArrayIndexOutOfBoundsException: length=19; index=-1 at android.icu.text.DigitList.isIntegral(DigitList.java:289) at android.icu.text.DecimalFormat.parse(DecimalFormat.java:2034) at android.icu.text.DecimalFormat.parse(DecimalFormat.java:1931) at java.text.DecimalFormat.parse(DecimalFormat.java:804) at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:2353) at java.text.SimpleDateFormat.parseInternal(SimpleDateFormat.java:1615) at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1528) at java.text.DateFormat.parse(DateFormat.java:360) at com.an.room.util.TimestampConverter.fromTimestamp(TimestampConverter.java:21) at com.an.room.dao.DaoAccess_Impl$4.compute(DaoAccess_Impl.java:218) at com.an.room.dao.DaoAccess_Impl$4.compute(DaoAccess_Impl.java:174) at android.arch.lifecycle.ComputableLiveData$2.run(ComputableLiveData.java:100) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636) at java.lang.Thread.run(Thread.java:764) 09

    It seems error occurred while converting time from timestamp to date. hope you will see that happened exactly.

    opened by shihabmi7 0
Owner
Anitaa Murthy
Android Developer/iOS Developer
Anitaa Murthy
A demo application that uses TMDB APIs to fetch the movie details and cache it using the Room DB.

TMDB App Tmdb sample project is a demo application that is based on modern Android architectures. It will fetch the data from the network and cache it

Clint Paul 38 Nov 28, 2022
Viacheslav Veselov 0 Jul 8, 2022
A simple chat demo for socket.io and Android

socket.io-android-chat This is a simple chat demo for socket.io and Android. You can connect to https://socket-io-chat.now.sh using this app. Installa

Naoyuki Kanezawa 1.9k Dec 30, 2022
A demo app to show how to detect screenshots taken by the user while using the app

Screenshot Detector A demo app to show how to detect screenshots taken by the user while using the app. Blog link Detect Screenshots in Android Screen

Nikit Bhandari 77 Dec 9, 2022
A sample Grocery Store app built using the Room, MVVM, Live Data, Rx Java, Dependency Injection (Kotlin Injection) and support Dark Mode

Apps Intro A sample Grocery Store app built using the Room, MVVM, Live Data, Rx Java, Dependency Injection (Kotlin Injection) and support Dark Mode In

Irsyad Abdillah 25 Dec 9, 2022
🧸 A demo Disney app using Jetpack Compose and Hilt based on modern Android tech stacks and MVVM architecture.

DisneyCompose A demo Disney app using compose and Hilt based on modern Android tech-stacks and MVVM architecture. Fetching data from the network and i

Jaewoong Eum 791 Dec 30, 2022
Demo app to showcase Sensor data using AIDL bound services.

AIDLServices Displays data related to TYPE_ROTATION_VECTOR sensor using AIDL Consist of aidlsdk module that expose sensor data Sample app to show the

Vikas Mane 3 May 26, 2021
PokeCard Compose is a demo app 100% write in Compose, Flow and Koin based on MVI Clean Architecture 🐱⚡️

A Pokemon Card demo app using Jetpack Compose and Koin based on MVI architecture. Fetching data from the network with Ktor and integrating persisted data in Room database with usecase/repository pattern.

Lopez Mikhael 104 Nov 27, 2022
👨‍💻 A demonstration modern Android development project with Jetpack(Compose, Room, ViewModel, Navigation), Hilt and based on MVVM by using Open Sky API. ✈️ 🌍

A demonstration modern Android development project with Jetpack(Compose, Room, ViewModel, Navigation), Hilt and based on MVVM by using Open Sky API.

Ismail Oguzhan Ay 13 Dec 4, 2022
A demonstration modern Android development project with Jetpack(Compose, Room, Flow, ViewModel, Navigation), Hilt and based on MVVM by using Github API.

A demonstration modern Android development project with Jetpack(Compose, Room, ViewModel, Navigation), Hilt and based on MVVM by using Github API.

Murat 2 Apr 11, 2022