Using Room Persistent Library to make a notebook : Part II

in #utopian-io6 years ago (edited)

What will I Learn

  • Using @Query in Room to perform database query
  • Getting the list of all notes saved in database and displaying it in the view
  • Using @Delete operation to delete note from the database

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

Previously we successfully inserted a note in the database using Room Persistent Library. Now we will get all the notes saved in database and show it in the list.
We will be using RecyclerView in order to display the list of notes in our MainActivity. So open content_main.XML remove the TextView and Add RecyclerView like this.

<android.support.v7.widget.RecyclerView
    android:id="@+id/show_notes_list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>

Now open your MainActiviy.java. In order to get the list of notes saved in database we already had defined the function getAllNote() in our NoteDao.class.

@Query("Select * from note")
List<Note> getAllNote();

This function returns all the notes saved in the database which we will display in a RecyclerView. Now let us talk about @Query annotation of Room Persistent library.
The @Query annotation is used to when we have to perform queries in the database. Here we have performed a simple query that returns the list of notes saved in the database. The value of the annotation returns the query to be performed. We can also pass argument in the function if we want to get only the notes of personal category.

@Query("SELECT * FROM note WHERE noteCategory LIKE :noteCategory")
public List<Note> findNoteAsPerCategory(String noteCategory);

Room supports named bind parameter :noteCategory to avoid any confusion between the method parameters and the query bind parameters.
Now if we add these lines of codes in our MainActivity then it will return the list of the notes which falls only under personal category.

NoteDatabase noteDatabase=NoteDatabase.getAppDatabase(this);
noteDatabase.newChatDAO().findNoteAsPerCategory("personal");

In this way we can perform various queries using @Query annotation in the corresponding Dao class. For now we will get the list of all notes and display it in a RecyclerView.
In order to display list of notes we will be making a custom adapter. So let us create a new java class and name it NoteAdapter

We will also require a layout to display our note. So let us create a new layout file and we will name it item_note.xml.

We will be adding Card view in our project in order to make our UI more appear like cards. For that open build.gradle (app level) and simply add a dependency:

implementation 'com.android.support:cardview-v7:27.1.0'

Now, open item_note.xml where we will design how will note look like. There are 4 TextViews to show the noteTitle, note, noreCategory and noteTime respectively. I have added cardview in this layout to make my notes look like cards. Here is the code for item_note

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >
    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardCornerRadius="8dp"
        android:layout_margin="@dimen/fab_margin"
        app:cardElevation="8dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/white"
            android:orientation="vertical"
           >
            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <ImageView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:scaleType="centerCrop"
                    android:src="@drawable/ic_show_category"/>
                <TextView
                    android:id="@+id/show_note_category"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:padding="3dp"
                    android:text="Category"
                    android:textColor="@android:color/white"
                    android:gravity="center"
                    />
            </RelativeLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:weightSum="2"
                android:padding="@dimen/fab_margin"

              >

            <TextView
                android:id="@+id/show_note_title"
                android:layout_width="0dp"
                android:layout_weight="1.3"
                android:textColor="@android:color/black"
                android:layout_height="wrap_content"
                android:textSize="20sp"
                android:text="Title" />

            <TextView
                android:id="@+id/show_note_date"
                android:layout_width="0dp"
                android:layout_weight="0.7"
                android:layout_height="wrap_content"
                android:text="Date" />
            </LinearLayout>

            <TextView
                android:id="@+id/show_note"
                android:paddingLeft="@dimen/fab_margin"
                android:paddingRight="@dimen/fab_margin"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textSize="18sp"
                android:textColor="@android:color/black"
                android:text="Note"
                android:paddingBottom="@dimen/fab_margin"/>
        </LinearLayout>

    </android.support.v7.widget.CardView>
</RelativeLayout>

Now, open NoteAdapter.java which will display our item in the recycler view. NoteAdapter will look like this

public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.ViewHolder>{

    List<Note> noteList;
    OnNoteLongPressedListener onNoteLongPressedListener;

    public NoteAdapter(List<Note> noteList,OnNoteLongPressedListener onNoteLongPressedListener) {
        this.noteList = noteList;
        this.onNoteLongPressedListener=onNoteLongPressedListener;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.item_note,null);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.bindView(noteList.get(position));

    }

    @Override
    public int getItemCount() {
        return noteList.size();
    }

    public void deleteNote(Note note){
        noteList.remove(note);
        notifyDataSetChanged();
    }

    class ViewHolder extends RecyclerView.ViewHolder{

        TextView noteTv,noteTitleTv,noteCategoryTv,noteDateTv;

        public ViewHolder(View itemView) {
            super(itemView);
            noteTv=itemView.findViewById(R.id.show_note);
            noteTitleTv=itemView.findViewById(R.id.show_note_title);
            noteCategoryTv=itemView.findViewById(R.id.show_note_category);
            noteDateTv=itemView.findViewById(R.id.show_note_date);
        }

        public void bindView(final Note note){
            noteTv.setText(note.getNote());
            noteTitleTv.setText(note.getNoteTitle());
            noteCategoryTv.setText(note.getNoteCategory());
            noteDateTv.setText(note.getNoteTime());
            itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    onNoteLongPressedListener.onNoteLongPressed(note);
                    return false;
                }
            });

        }
    }

    interface OnNoteLongPressedListener{
        void onNoteLongPressed(Note note);
    }
}

Here we can see an interface name OnNoteLongPressedListener. This interface is used so that we can add onLongPressdListener in our list item. We are adding onLongPressedListener so that we can delete out notes when user presses the note for long time.
For that first let us set up adapter for our RecyclerView in our MainActivity.
In order to populate notes in our Recycler view we will have to write following lines of code.

LinearLayoutManager layoutManager=new LinearLayoutManager(this);
 layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
 showNotesList.setLayoutManager(layoutManager);

noteAdapter=new NoteAdapter(noteDatabase.newNoteDAO().getAllNote(), new NoteAdapter.OnNoteLongPressedListener() {
     @Override
     public void onNoteLongPressed(Note note) {

         showDeleteNoteDialog(note);
     }
 });
 showNotesList.setAdapter(noteAdapter);

Here we have called showDeleteNoteDialog() method which will show a dialog asking user to delete the note or not. It is a very simple task to delete a note using room persistent library. We had already defined the delete method in our NoteDao.java class so by making call to that particular function we can delete our note.

noteDatabase.newNoteDAO().deleteNote(note);
noteAdapter.deleteNote(note);

The first line of code will delete the note from our database and the second line of code will update our RecyclerView instantly so that we shouldn’t refresh the activity to view whether the note has been deleted or not.
We will also be displaying the total no of notes in the top right corner of our toolbar. So now open activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
    tools:context="com.programminghub.mypersonalnotebook.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

        <TextView
            android:id="@+id/show_no_of_notes"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="@dimen/fab_margin"
            android:textSize="25sp"
            android:textStyle="bold"
            android:text="3"
            android:textColor="@android:color/white"/>
        </RelativeLayout>
    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@drawable/ic_add_note" />

</android.support.design.widget.CoordinatorLayout>

In order to get the total no of count of notes we have written a query in our Dao class like this:

@Query("Select COUNT(note) from note")
public Integer getTotalNoteCount();

This will return the total no of notes in database.
Now open your MainActivity.java and in order to get total no of notes and display it in top right corner of toolbar write the code:

showNoOfNotes.setText(String.valueOf(noteDatabase.newNoteDAO().getTotalNoteCount()));

Here we are getting total no of notes and wrapping up Integer value to String so that we can display it in TextView. The final code of MainActivity looks like this:

public class MainActivity extends AppCompatActivity {

    RecyclerView showNotesList;
    FloatingActionButton addNotes;
    NoteDatabase noteDatabase;
    NoteAdapter noteAdapter;
    TextView showNoOfNotes;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        initView();
        defineView();
        bindView();
        addClickListeners();


    }

    private void initView(){
        noteDatabase=NoteDatabase.getAppDatabase(this);

    }
    private void defineView(){
        addNotes= (FloatingActionButton) findViewById(R.id.fab);
        showNotesList=(RecyclerView) findViewById(R.id.show_notes_list);
        showNoOfNotes=findViewById(R.id.show_no_of_notes);

    }
    private void bindView(){
        LinearLayoutManager layoutManager=new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        showNotesList.setLayoutManager(layoutManager);

        showNoOfNotes.setText(String.valueOf(noteDatabase.newNoteDAO().getTotalNoteCount()));

       noteAdapter=new NoteAdapter(noteDatabase.newNoteDAO().getAllNote(), new NoteAdapter.OnNoteLongPressedListener() {
            @Override
            public void onNoteLongPressed(Note note) {

                showDeleteNoteDialog(note);
            }
        });
        showNotesList.setAdapter(noteAdapter);
    }
    private void addClickListeners(){
        addNotes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent addNoteIntent=new Intent(MainActivity.this,AddNotesActivity.class);
                startActivity(addNoteIntent);
            }
        });
    }



    private void showDeleteNoteDialog(final Note note){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("Delete entry")
                .setMessage("Are you sure you want to delete this note?")
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // continue with delete
                        noteDatabase.newNoteDAO().deleteNote(note);
                        noteAdapter.deleteNote(note);
                        showNoOfNotes.setText(String.valueOf(noteDatabase.newNoteDAO().getTotalNoteCount()));
                    }
                })
                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setIcon(android.R.drawable.ic_dialog_alert)
                .show();
    }




}

Now lets run our application.
Our first screen will MainActivity will load and it will show all the list of Notes that we have saved in our database:

If you long press on the note then a dialog will appear which asks your permission to delete the note like this:

It also shows the total no of notes in our database in the top right corner of our toolbar:

So in this tutorial we learnt to perform various query to get the notes and we also learnt to delete the note from the database using room persistent library. In the next session we will be updating the note and we will be refining the UI of AddNoteActivity.

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

Curriculam

Using Room persistent library to make a notebook in Android



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Your contribution cannot be approved because it does not follow the Utopian Rules.

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

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

@cha0s0000 please update the right repository if possible

Thank you for the contribution. It has been approved.

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

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

Achievements

  • WOW WOW WOW People loved what you did here. GREAT JOB!
  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • 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.27
TRX 0.11
JST 0.031
BTC 67241.02
ETH 3727.25
USDT 1.00
SBD 3.77