1 of 22

Exercise session 6

05.12.2017

2 of 22

Overview

We’ll create a notes app.

With EditText, Button and RecyclerView

We’ll save the notes to the database.

On user click we’ll add note to the database

User click on note we will remove it from database

3 of 22

What is Room?

Room persistence library provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.

4 of 22

There are 3 major components in Room

  • DataBase - Contains the database holder and serves as the main access point
  • Entity - Represents a table within the database.
  • DAO - Contains the methods used for accessing the database.

5 of 22

Let’s Begin

You can always use This project as a reference

And Room training Guide can be helpful too.

6 of 22

Step1- Create a new project

For help go to the lecture slides:goo.gl/9RwRvw

Or

Clone goo.gl/UpAE66

7 of 22

Step2- Add Room dependencies

Add Room to dependencies in build.gradle(app) file:

implementation "android.arch.persistence.room:runtime:1.0.0"�annotationProcessor "android.arch.persistence.room:compiler:1.0.0"

GitHub commit: https://goo.gl/TfmEpH

8 of 22

Step3- Create Note Entity class

  • Create Note class and mark it with @Entity annotation
  • Create id field and mark it as @PrimaryKey(autoGenerate = true)
  • Add 2 Strings for the note title and body
  • Add getters and setters for the fields.

@Entitypublic class Note {@PrimaryKey(autoGenerate = true)private int id;

GitHub commit: https://goo.gl/3jE2dd

9 of 22

Step4- Add AppDatabase class

  • AppDatabase class must to extend RoomDatabase class
  • Annotate your class with @Database(entities = {Note.class}, version = 1)
  • You should follow the singleton design pattern when instantiating an AppDatabase object, as each RoomDatabase instance is fairly expensive.
  • Add allowMainThreadQueries() for testing purposes. Please note that in real project all interactions with the database must be executed in the background.

INSTANCE = Room.databaseBuilder(context.getApplicationContext(),AppDatabase.class, DATABASE_NAME).allowMainThreadQueries().build();

GitHub commit: https://goo.gl/Hx4BBa

10 of 22

Step5- Add NoteDao interface

  • Create NoteDao interface and mark it with @Dao annotation
  • DAO - Data Access Object - is an abstract class or interface that includes methods to define database queries.

*** Do not forget to add abstract method in AppDatabase that returns NoteDao

public abstract NoteDao noteDao();

GitHub commit: https://goo.gl/gD3TPc

11 of 22

NoteDao - query data

@Query("SELECT * FROM Note")List<Note> getAll();��@Query("SELECT * FROM Note WHERE id = :id")Note getNoteById(int id);

12 of 22

NoteDao - insert row/s

@Insert(onConflict = OnConflictStrategy.REPLACE)void insertAll(Note... notes);��@Insert(onConflict = OnConflictStrategy.REPLACE)void insert(Note note);

13 of 22

NoteDao - delete row

@Deletevoid delete(Note note);

14 of 22

Step6 - Add RecyclerView

  • Add RecylerView. For help go to the lecture slides.
  • Create adapter that would work with List of Note objects
  • Create some fake data to test your RecyclerView

mNotesAdapter = new NotesAdapter(this, getNoteList());�recyclerView.setAdapter(mNotesAdapter);

private List<Note> getNoteList() {List<Note> list = new ArrayList<>();� list.add(createNote("Title 1", "Body 1"));� list.add(createNote("Title 2", "Body 2"));� list.add(createNote("Title 3", "Body 3"));return list;}

private Note createNote(String title, String body) {Note note = new Note();� note.setTitle(title);� note.setBody(body);return note;}

GitHub commit: https://goo.gl/wbJstm

15 of 22

Step7- Add fake data to DB and use it in adapter

private List<Note> getNoteList() {AppDatabase.getInstance(this).noteDao().insertAll(� createNote("Title 1", "Body 1"),� createNote("Title 2", "Body 2"),� createNote("Title 3", "Body 3"));return AppDatabase.getInstance(this).noteDao().getAll();}

GitHub commit: https://goo.gl/ot6o3h

16 of 22

Step8 - Delete notes from DB on item click

  • Delete row with: AppDatabase.getInstance(this).noteDao().delete(note);
  • Remove item from the list and notify adapter

public void onClick(View view) {int position = (int) view.getTag();Note note = mNoteList.get(position);� mListener.onDeleteNote(note);� mNoteList.remove(note);� notifyItemRemoved(position);� notifyItemRangeChanged(position, mNoteList.size());}

GitHub commit: https://goo.gl/SYuyfb

17 of 22

Step9 - Remove fake data

GitHub commit: https://goo.gl/kTpB9b

18 of 22

Step10- Add adding note UI elements

  • Add EditText for Title and for Body of the note
  • Add Button “Add Note”.

GitHub commit: https://goo.gl/RVhCxD

19 of 22

Step11- Add note to DB

When user click on “Add note” button get inputs from EditTexts and save them to the database

AppDatabase.getInstance(this).noteDao().insert(note);

GitHub commit: https://goo.gl/k8m3QQ

20 of 22

Step12- Update the list when new note is added

MainActivity

NotesAdapter

List<Note> updatedList = getNoteList();�mNotesAdapter.updateList(updatedList);� � �public void updateList(List<Note> updatedList) {� mNoteList = updatedList;� notifyDataSetChanged();}

GitHub commit: https://goo.gl/946ZCe

21 of 22

DONE?

That’s amazing! Good for you!!

If you have even a small question- don’t forget to ask the mentors:

At the class or on Slack.

22 of 22

Kudos!!

You’re all done with exercise 6!

See you next time!