Using Room persistent library to make a notebook in Android

in #utopian-io8 years ago (edited)

What will I learn?

  • What is Room persistent library?
  • what are the advantages of using it
    *Setting up room persistent library in our android project
  • Saving our first note in our application

Requirement

  • A PC/laptop with any Operating system such as Linux, Mac OSX, Windows OS
  • Preinstalled Android Studio, Android SDK and JDK

Note: This tutorial is performed in Android Studio in laptop with Windows 10 Home, 64 bit OS

Difficulty

Anybody with basic knowledge of android can grasp the tutorial content.

Tutorial Content

In order to make a notebook in android we have to make a interface where user can save the note and our note should be stored in our mobile device so that they can view the notes at their desired time. There are many techniques for saving data in our local device like Shared Preferences, Internal Storage, External Storage and SQLite.

Android provides support for application to use SQLite database for data storage. But we should have a prior knowledge about queries in order to use SQLite. That’s where Room persistent library shines in.

So, what is room persistent library?

It is not the replacement of SQLite database instead it provides an abstraction layer over SQLite that means it acts as an intermediate between programmer and SQLite database and hides the implementation details of SQLite and makes the task of programmer easier to access the databse simply by implementing annotations.

Advantage of using Room Persistent library:

So why do we have to chose Room persistent library while there are many options for creating database in android application. We can create database in many ways either by using native library that is SQLite, or using third party libraries like: OrmLite, Realm etc. But none of the libraries provide following advantages
• we do not have to write boilerplate codes and we don’t have to worry about the queries.
• API provided by SQLite are a bit low level and is bit time consuming to understand.
• compile time verification of the SQL queries. Initially the application did not show error at the compile time while there were errors in the database queries which created runtime crashes. Room find those errors in compile time.

There are three major components in Room. They are:
Entity: It represents the table which is to be created in the databse. Entity are made from the model where we define the structure of our data. It is annotated using @Entity
Database: It is annotated using @Database. As per the documentation the class annotated with @databse must contain:
• Be an abstract class that extends RoomDatabase.
• Include the list of entities associated with the database within the annotation.
• Contain an abstract method that has 0 arguments and returns the class that is annotated with @Dao.

DAO: It stands for Data Access Model and it contains the operation to be performed in the database and it contains methods for accessing the database. It is annotated using @Dao .

Now let us start coding and making you own notebook.
First create a new project. I have given it the name MyPersonalNotebook

We will select the minimum API level to be 15 to make it compatible from android devices from IceCreamSandwich.

Now we select BasicActivity .

We will name the activity to default that is MainActivity which will be our landing activity.

The project is now all setup. now we have to setup the room library in our project. For that open the build.gradle file and add the following two lines:

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

After adding these two lines in the gradle sync the project and we are all set to go.
In our MainActivity we will be showing all the list of the notes and if we press the button we will be navigated to the activity where we will add the notes.
Now first of all let us create a new activity where we will be adding notes.

We will be naming it AddNotesActivity.

Now creating our first Entity. Create a new Java class named Note.java. Note is an entity which will contain the noteTitle, noteDate, note and noteCategory. We will also be adding noteId in order to uniquely identify each note. In order to make Note recognize as Enity in Room we simply have to annotate the class with @Entity.
In order to create column we can simply annotate the attribute of the entity that is noteTitle, noteDate, note, noteCategory with @ColumnInfo.

@Entity
public class Note {

    @PrimaryKey
    private Integer noteId;

    public Integer getNoteId() {
        return noteId;
    }

    public void setNoteId(Integer noteId) {
        this.noteId = noteId;
    }

    @ColumnInfo
    private String noteTitle;

    @ColumnInfo
    private String noteCategory;

    @ColumnInfo
    private String noteTime;

    @ColumnInfo
    private String note;

    
    public Note(String noteTitle, String noteCategory, String             noteTime, String note) {
    this.noteTitle = noteTitle;
    this.noteCategory = noteCategory;
    this.noteTime = noteTime;
    this.note = note;
    }



    public String getNoteTitle() {
        return noteTitle;
    }

    public void setNoteTitle(String noteTitle) {
        this.noteTitle = noteTitle;
    }

    public String getNoteCategory() {
        return noteCategory;
    }

    public void setNoteCategory(String noteCategory) {
        this.noteCategory = noteCategory;
    }

    public String getNoteTime() {
        return noteTime;
    }

    public void setNoteTime(String noteTime) {
        this.noteTime = noteTime;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }
}

It looks something like this. Here Note is the entity we will be table name in SQLite and noteTitle, note, noteTime and noteCategory which are attribute of the note are actually the column of the table named note. @ColumnInfo is an annotation used for defining the corresponding column name in database if we want to change the column nave then we can simply do it by

@ColumnInfo(name="name_you_want_to _give")

Adding DAO
Once we have defined our Entity we also have to add the corresponding DAO(Data access object) in order to perform operation in our database. DAO contains necessary operation that we will be doing in our database. Here @Insert, @Update and @Delete are used correspondingly for inserting, updating and deleting the note. We use @Query for creating queries like: getting all notes from database

@Dao
public interface NoteDao {

    @Insert
    void insertNote(Note note);

    @Update
    void updateNote(Note note);
    
    @Delete
    void deleteNote(Note note);
    
    @Query("Select * from note")
    List<Note> getAllNote();

}

Database declaration
Now we have to create a database holder. Here we have to define the entities to our model classes and the database version we are using. We use getAppDatabase method to get the instance of the database and by usng Room.databaseBuilder we are constructing a databse named "note-database"

@Database(entities = {Note.class}, version = 1)
public abstract class NoteDatabase extends RoomDatabase {
    private static NoteDatabase INSTANCE;
    
    public abstract NoteDao newNoteDAO();

    public static NoteDatabase getAppDatabase(Context context) {
        if (INSTANCE == null) {
            INSTANCE =
                    Room.databaseBuilder(context.getApplicationContext(), NoteDatabase.class, "note-database")
                         .allowMainThreadQueries()
                            .build();
        }
        return INSTANCE;
    }
    public static void destroyInstance() {
        INSTANCE = null;
    }

}

Now lets move to our AddNotesActivity. We will first create the layout to add notes. So open acitivity_add_notes.xml and remove the code for Floating action button as we don’t want it.
Now open content_add_notes where we will be adding two EidtText to take note title and note. We will also have one spinner to make user select note category and finally one button to save the note.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.programminghub.mypersonalnotebook.AddNotesActivity"
    tools:showIn="@layout/activity_add_notes">

    <EditText
        android:id="@+id/note_title"
        android:hint="Title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/note"
        android:hint="Note"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Spinner
        android:id="@+id/note_category"
        android:entries="@array/note_category"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/add_note"
        android:text="Add Note"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

Now after making the layout we will be working on AddNoteActivity.java to accept user input and save the note in the database using Room persistent library.
We should first initialize the database

NoteDatabase noteDatabase;
noteDatabase=NoteDatabase.getAppDatabase(this);

To add things in the database we now need to invoke

noteDatabase.newNoteDAO().insertNote(new Note(noteTitle,noteCategory,sdf.format(time),noteStr));

The final code of AddNotesActivity looks like this:

public class AddNotesActivity extends AppCompatActivity {

    EditText noteTitleEt,noteEt;
    Spinner noteCategorySpnr;
    Button addNote;
    NoteDatabase noteDatabase;
    private final String TAG=AddNotesActivity.class.getSimpleName();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_notes);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        initView();
        defineView();
        addClickListener();

    }
   
    private void initView(){
        noteDatabase=NoteDatabase.getAppDatabase(this);
    }
    
    //definig views 
    private void defineView(){
        noteTitleEt=findViewById(R.id.note_title);
        noteEt=findViewById(R.id.note);
        noteCategorySpnr=findViewById(R.id.note_category);
        addNote=findViewById(R.id.add_note);
    }
    //handling all the click function in a single funcition
    private void addClickListener(){
        addNote.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(validate()){
                    Long time=System.currentTimeMillis();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    noteDatabase.newChatDAO().insertNote(new Note(noteTitle,noteCategory,sdf.format(time),noteStr));

                    noteAddedSuccesfulOrNot();
                }

            }
        });


        noteCategorySpnr.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                noteCategory=noteCategorySpnr.getSelectedItem().toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    //to check whether the note is added succesfully or not
    private void noteAddedSuccesfulOrNot(){
        List<Note> notes=noteDatabase.newChatDAO().getAllNote();
        if(notes.size()>0){
            for (int i=0;i<notes.size();i++){
                Log.d(TAG,"note you aadded to daatabase is:"+notes.get(i).getNote());
            }
        }
    }

    String noteCategory,noteStr,noteTitle;
    //to validate if null data is added in the database or not
    private boolean validate(){
        boolean valid=false;
        noteStr=noteEt.getText().toString();
        noteTitle=noteTitleEt.getText().toString();
        if(TextUtils.isEmpty(noteTitle))
            noteTitleEt.setError("Required");
        else if(TextUtils.isEmpty(noteStr))
            noteEt.setError("Required");
        else
            valid=true;
        return valid;
    }

}

Now if we press the add note button then our note will be inserted in the database.
In order to call AddNoteActivity now open the MainActivity and inside the the click event listener of fab button just add two lnes of codes:

Intent addNoteIntent=new Intent(MainActivity.this,AddNotesActivity.class);
startActivity(addNoteIntent);

This will call AddNotesActivity after we press the fab button. Now let's run the application
Initially you will get the MainActivity like this:

Now press the fab button then you can get the AddNoteActivity where you will add note using room library.

If you now see your log then you can see the output as:

All above codes are available in my github link. Click here to download.

Now in the next series we will display all the added notes in our MainActivity and make the designs more user interactive.



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Unfortunately, this contribution cannot be accepted with the currently selected repository. It contains the app samples.

Edit: It has been approved again. The repository was changed to https://github.com/aosp-mirror/platform_frameworks_support

You can contact us on Discord.
[utopian-moderator]

Hey @shreyasgune, I just gave you a tip for your hard work on moderation. Upvote this comment to support the utopian moderators and increase your future rewards!

This post has received a 15.85 % upvote from @boomerang.

thank you for info

Hey @programminghub I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • You are generating more rewards than average for this category. Super!;)
  • Seems like you contribute quite often. AMAZING!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

Coin Marketplace

STEEM 0.04
TRX 0.32
JST 0.074
BTC 63499.35
ETH 1673.21
USDT 1.00
SBD 0.41