Using room persistent library to make a notebook in android : Part III

Words
804
Reading
4 min
Listen
Play
9y

What will I Learn?

  • Making NoteDetailActivity display the note detail
  • Sending a message from one activity to another
  • Using @Update to update the note

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 on the laptop with Windows 10 Home, 64 bit OS

Difficulty

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

Tutorial Content

Previously we showed the list of saved notes in list learned about @Query and we also deleted the note.
Now in this part, we will be learning to update the note and making the view of content_add_note.xml more attractive.
We will also be making Note detail activity where user can view the detail of the note. From there user can edit the note if they want.
So, let us create a new Activity and name it NoteDetailActivity.java

We will add click listener in the floating action button so that user can be navigated to edit note activity. Now open content_note_detail.xml and write the following code.

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.programminghub.mypersonalnotebook.NoteDetailActivity"
    tools:showIn="@layout/activity_note_detail">

  <include layout="@layout/item_note"/>
</RelativeLayout>

We can simply include the layout item_note.xml so that we should not rewrite the code again. In order to add click listener to the note we will have to add one more interface in our NoteAdapter.java

interface onNotePressedListener{
    void onNotePressedListener(Note note);
}

After this we will get the note in which the user pressed in our MainActivity.java like this:

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

        showDeleteNoteDialog(note);
    }
}, new NoteAdapter.onNotePressedListener() {
    @Override
    public void onNotePressedListener(Note note) {
        // handle intent to note detail
    }
});

Here we have handled two click listners one is onNoteLongPressed and the second one is onNotePressedListener. We have used onNoteLongPressed to delete the note so we will be using onNotePressedLIstener to note detail to user. We can achieve this simply by passing intent to NoteDetailActivity.java. This can be achieved by:

Intent notePressedIntent=new Intent(MainActivity.this,NoteDetailActivity.class);
notePressedIntent.putExtra(NoteDetailActivity.KEY_NOTE_DETAIL_INTENT,note);
startActivity(notePressedIntent);

We have passed the Note through intent so that we can show the detail of the note in which user pressed. We can pass an object through Intent by implementing Serializable or Parceble in our object class file.
We can get the passed Intent in our NoteDetailActivity simply by:

Note note= (Note) getIntent().getSerializableExtra(KEY_NOTE_DETAIL_INTENT);

In this way we can pass objects or say message from one Activity to another.

We will not be making a separate Activity for updating our note we will be working on AddNotesActivity in order to update our note. We will let the user update the note when they press the note.
We can achieve this simply by sending a flag when AddNotesActivity is opened. If the flag is true we will add note and if the flag is false then we will be editing the note.
We will be sending the flag in similar way we passed the object.
So let us open MainActivity and in the click event of fab button where we previously opened AddNoteActivity directly we will be passing a false flag which will tell AddNoteActivity that we are going to add the note.

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

So here if we send false in KEY_IS_UPDATE the user will be adding note and if we send the true value in KEY_IS_UPDATE then the user will edit the note.
now open NoteDetailActivity.java and inside the fab button click event add the following lines of code:

Intent editNoteIntent=new Intent(NoteDetailActivity.this,AddNotesActivity.class);
editNoteIntent.putExtra(AddNotesActivity.KEY_IS_UPDATE,true);
editNoteIntent.putExtra(AddNotesActivity.KEY_NOTE_ID,note.getNoteId());
startActivity(editNoteIntent);

Here we are sending the true value which means the user wants to update the note. We should also pass the noteId because we should retrieve the note in order to update it. Now open AddNoteActivity.java

if(getIntent().hasExtra(KEY_IS_UPDATE)){
    isUpdate=getIntent().getExtras().getBoolean(KEY_IS_UPDATE);
    if(isUpdate){
        noteId=getIntent().getExtras().getInt(KEY_NOTE_ID);
    }
}

Here we get the value of isUpdate and if is update is true we also get the value of noteId so that we can update our note accordingly.

if(isUpdate) {
    addNote.setText("Update");
    Note note=noteDatabase.newNoteDAO().getNoteAsPerId(noteId);
    noteTitleEt.setText(note.getNoteTitle());
    noteEt.setText(note.getNote());
    String categoryList[]=getResources().getStringArray(R.array.note_category);
    List list = Arrays.asList(categoryList);
    noteCategorySpnr.setSelection(list.indexOf(note.getNoteCategory()));
}

We have written this code so that previous note will be displayed in the TextViews so that the user can know what they had inserted before.
Now, we can simply update the note by calling the function in our Dao class
noteDatabase.newNoteDAO().updateNote(note);
This will update the note. The final code of AddNoteActivity looks like this:

public class AddNotesActivity extends AppCompatActivity {

    EditText noteTitleEt,noteEt;
    Spinner noteCategorySpnr;
    Button addNote;
    NoteDatabase noteDatabase;
    private final String TAG=AddNotesActivity.class.getSimpleName();

    public static final String KEY_IS_UPDATE="isUpdate";
    Boolean isUpdate;
    Integer noteId;
    public static final String KEY_NOTE_ID="noteId";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_notes);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if(getIntent().hasExtra(KEY_IS_UPDATE)){
            isUpdate=getIntent().getExtras().getBoolean(KEY_IS_UPDATE);
            if(isUpdate){
                noteId=getIntent().getExtras().getInt(KEY_NOTE_ID);
            }
        }
        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);

        if(isUpdate) {
            addNote.setText("Update");
            Note note=noteDatabase.newNoteDAO().getNoteAsPerId(noteId);
            noteTitleEt.setText(note.getNoteTitle());
            noteEt.setText(note.getNote());
            String categoryList[]=getResources().getStringArray(R.array.note_category);
            List list = Arrays.asList(categoryList);
            noteCategorySpnr.setSelection(list.indexOf(note.getNoteCategory()));
        }

    }
    //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");
                    Note note=new Note(noteTitle, noteCategory, sdf.format(time), noteStr);
                    if(isUpdate){
                        note.setNoteId(noteId);
                        Log.d(TAG,"note id is:"+note.getNoteId());
                        Log.d(TAG,"note title is:"+noteTitle);
                        Log.d(TAG,"note is:"+noteStr);
                        Log.d(TAG,"note category is:"+noteCategory);
                        Log.d(TAG,"inside note update");
                        noteDatabase.newNoteDAO().updateNote(note);
                        Log.d(TAG,"note updated succesfully");

                    }else {
                        Log.d(TAG,"inside adding note");
                        noteDatabase.newNoteDAO().insertNote(note);
                    }
                    Intent navigateToMain=new Intent(AddNotesActivity.this,MainActivity.class);
                    startActivity(navigateToMain);
                }

            }
        });


        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.newNoteDAO().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 let us open content_add_note.xml.

<?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"
    android:layout_margin="@dimen/fab_margin"
    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:padding="@dimen/fab_margin"
        android:background="@drawable/drawable_background_tv"
        android:layout_width="match_parent"
        android:layout_marginBottom="@dimen/fab_margin"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/note"
        android:hint="Note"
        android:padding="@dimen/fab_margin"
        android:background="@drawable/drawable_background_tv"
        android:layout_width="match_parent"
        android:layout_marginBottom="@dimen/fab_margin"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_width="match_parent"
        android:padding="@dimen/fab_margin"
        android:background="@drawable/drawable_background_tv"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/fab_margin">
    <Spinner
        android:id="@+id/note_category"
        android:entries="@array/note_category"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
      />
    </LinearLayout>

    <Button
        android:id="@+id/add_note"
        android:text="Add Note"
        android:background="@color/colorPrimary"
        android:textColor="@android:color/white"
        android:textSize="20sp"
        android:textAllCaps="false"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

I have added some backgrounds in the TextView to make it more attractive. You can make your view as you want.
The final output looks like this:

This is our landing page where we will view the list of notes we had saved in database.

This is our second activity where we will add our note

We can also delete the note by pressing on the note for long time

We can also view the note detail and edit the note by pressing on fab button

Here we can edit the note and update it

In this way we have created a simple android application notebook where user can add, edit, delete notes by using room persistent library.

All above codes can be found in my github link. Click here to download.

Curriculam

Using Room persistent library to make a notebook in Android

Using Room Persistent Library to make a notebook : Part II



Posted on Utopian.io - Rewarding Open Source Contributors

Using room persistent library to make a notebook in android : Part ... | Ecency