I was trying to make this Notepad application using the Android Jetpack Architecture Components of LiveData, ViewModel, Room, and DataBinding. The app contains three activity layouts, a menu layout, a toolbar layout that I plan to use for all these activities. This toolbar layout contains a textView that will be used for setting the toolbar layout using DataBinding.
The following are the important XML files:
custom_notes_toolbar_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="toolbarTitle"
type="String" />
</data>
<androidx.appcompat.widget.Toolbar
android:id="@+id/activity_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/color_primary">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:fontFamily="@font/nunito_semibold"
android:text="@{toolbarTitle}"
android:textColor="@color/muted_white"
android:textSize="20sp" />
</androidx.appcompat.widget.Toolbar>
</layout>
activity_display_note.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:bind="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".view.DisplayNoteActivity">
<data>
<variable
name="toolbarTitle"
type="String" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/toolbar_linear_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<include
android:id="@+id/toolbar"
layout="@layout/custom_notes_toolbar_layout"
bind:toolbarTitle="@{toolbarTitle}" />
</com.google.android.material.appbar.AppBarLayout>
</LinearLayout>
<TextView
android:id="@+id/title_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="@font/nunito"
android:padding="15dp"
android:textSize="25sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/toolbar_linear_layout" />
<TextView
android:id="@+id/content_text_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:fontFamily="@font/nunito_extralight"
android:gravity="start"
android:padding="15dp"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/title_text_view" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/edit_note_floating_action_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="30sp"
android:layout_marginBottom="30sp"
android:contentDescription="@string/edit_note"
android:src="@drawable/ic_edit"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
display_note_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/delete_menu_option"
android:icon="@drawable/ic_delete"
android:title="@string/delete_menu_string"
app:showAsAction="always" />
</menu>
DisplayNoteActivity.java
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.arpansircar.java.notepadapplicationusingmvvm.R;
import com.arpansircar.java.notepadapplicationusingmvvm.databinding.ActivityDisplayNoteBinding;
import com.arpansircar.java.notepadapplicationusingmvvm.model.Constants;
import com.arpansircar.java.notepadapplicationusingmvvm.room.NotesEntity;
import com.arpansircar.java.notepadapplicationusingmvvm.viewmodel.DisplayNoteActivityViewModel;
/**
* The DisplayNoteActivity displays the contents of a single note.
* Upon clicking a certain note in the NotesActivity RecyclerView, the user is guided to this activity and the selected note is displayed here.
* In this activity, the user can view, delete, or update the particular note as required.
* All such changes are reflected back in the NotesActivity.
*/
public class DisplayNoteActivity extends AppCompatActivity implements View.OnClickListener {
private ActivityDisplayNoteBinding activityDisplayNoteBinding;
private NotesEntity currentNoteEntity;
private DisplayNoteActivityViewModel displayNoteActivityViewModel;
/*The onCreate method is the first method to be executed when the application starts up.
* Here, those methods are called that are to be executed only once.
* This particular method executes the setToolbarMethod(), getIntentData(), and initializeViewModel() methods.
* The setToolbarMethod() sets the toolbar which contains the functionality for deleting a note.
* The getIntentData() fetches complete note details including the note id, title, content, and date.
* The initializeViewModel() method creates an instance of the AddEditNoteActivityViewModel class.*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityDisplayNoteBinding = DataBindingUtil.setContentView(this, R.layout.activity_display_note);
setToolbarMethod();
getIntentData();
initializeViewModel();
}
/*onStart() lifecycle callback method is executed after onCreate().
* In this callback method, two methods are executed.
* The setObserver() method activates the observer to check any changes arising within the LiveData object.
* The setOnClickListenerMethod() intercepts any clicks occurring within the activity.*/
@Override
protected void onStart() {
super.onStart();
startObserver();
setOnClickListenerMethod();
}
/*The onCreateOptionsMenu(...) creates the menu options in the toolbar.
* Here, a single menu option is used to delete the note being viewed.*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.display_note_menu, menu);
return true;
}
/*The onOptionsItemSelected(...) method intercepting the clicks occurring on the menu options.
* Here, a single menu option will be displayed to allow the user to delete the particular note being viewed.
* Upon being pressed, this delete option will trigger the deleteNoteMethod() and the activity will be removed from the view.*/
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.delete_menu_option) {
deleteNoteMethod();
finish();
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
/*The setToolbarMethod() sets the custom toolbar in the activity.*/
private void setToolbarMethod() {
Toolbar toolbar = activityDisplayNoteBinding.toolbar.activityToolbar;
activityDisplayNoteBinding.setToolbarTitle(getString(R.string.display_activity_title));
setSupportActionBar(toolbar);
}
/*The initializeViewModel() creates an instance to the DisplayNoteActivityViewModel for communicating with the database.*/
private void initializeViewModel() {
displayNoteActivityViewModel = new ViewModelProvider(this).get(DisplayNoteActivityViewModel.class);
}
/*The setObserverMethod() method is used simply activates the observer.*/
private void startObserver() {
final Observer<NotesEntity> notesEntityObserver = notesEntity -> {
this.currentNoteEntity = notesEntity;
setNoteInActivity(notesEntity);
};
displayNoteActivityViewModel.selectNoteMethod(getIntentData()).observe(this, notesEntityObserver);
}
/*The setOnClickListenerMethod() method sets the onClickListener to the floating action button used in the activity.*/
private void setOnClickListenerMethod() {
activityDisplayNoteBinding.editNoteFloatingActionButton.setOnClickListener(this);
}
/*The setNoteInActivity(...) method sets the NotesEntity instance within the activity.
* The method is triggered by any changes occurring within the LiveData instance.
* A try-catch block is placed to handle the NullPointerExceptions that arise when a note is deleted.
* The NullPointerException occurs as the observer observes a change and tries to fetch the changed note.
* But this isn't possible as the note has already been deleted from the database, causing the exception.
* Therefore, the catch block handles the exception by removing the activity from view and showing a Toast message.*/
private void setNoteInActivity(NotesEntity notesEntity) {
try {
activityDisplayNoteBinding.titleTextView.setText(notesEntity.getTitle());
activityDisplayNoteBinding.contentTextView.setText(notesEntity.getContent());
} catch (NullPointerException nullPointerException) {
finish();
}
}
/*The getIntentData() method extracts the noteID from the intent.*/
private int getIntentData() {
Intent intent = getIntent();
return intent.getIntExtra(Constants.COLUMN_ID, -1);
}
/*The deleteNoteMethod() deletes a note from the database and the NotesActivity.
* The method is triggered by the onOptionsItemSelected() method when the user presses the delete menu option in the toolbar.*/
private void deleteNoteMethod() {
displayNoteActivityViewModel.deleteNoteMethod(currentNoteEntity);
Toast.makeText(this, "Note Deleted", Toast.LENGTH_SHORT).show();
}
/*The onClick(...) method intercepts all clicks performed in the current activity.
* When the floating action button is clicked, the "edit" function, note id, title, content, and date is bundled into the intent as extras.
* Finally, this data is sent into the AddEditNoteActivity and the activity is started.*/
@Override
public void onClick(View view) {
if (view == activityDisplayNoteBinding.editNoteFloatingActionButton) {
Intent editNoteIntent = new Intent(DisplayNoteActivity.this, AddEditNoteActivity.class);
editNoteIntent.putExtra("function", "edit");
editNoteIntent.putExtra(Constants.COLUMN_ID, currentNoteEntity.getId());
editNoteIntent.putExtra(Constants.COLUMN_NAME_TITLE, currentNoteEntity.getTitle());
editNoteIntent.putExtra(Constants.COLUMN_NAME_CONTENT, currentNoteEntity.getContent());
editNoteIntent.putExtra(Constants.COLUMN_NAME_DATE, currentNoteEntity.getDate());
startActivity(editNoteIntent);
}
}
}
Now, the problem arises in the setToolbarMethod():
private void setToolbarMethod() {
Toolbar toolbar = activityDisplayNoteBinding.toolbar.activityToolbar;
activityDisplayNoteBinding.setToolbarTitle(getString(R.string.display_activity_title));
setSupportActionBar(toolbar);
}
When I try out this method, it causes two Toolbar titles to be set, namely, the name of the app and the title that I'm trying to set through DataBinding.
I tried to remove the setToolbarMethod() completely, but that means that I wouldn't be able to set the Toolbar, in effect, I wouldn't be able to set the menu either. And the reason I'm using DataBinding to set the toolbar title rather than using setTitle() method provided is that I want a different font for the title text than provided by default by this method.
I know that this question might sound a little confusing. If required, I can provide details as required. Thanks for any help.
Let's dissect this:
<androidx.appcompat.widget.Toolbar
android:id="@+id/activity_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/color_primary">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:fontFamily="@font/nunito_semibold"
android:text="@{toolbarTitle}"
android:textColor="@color/muted_white"
android:textSize="20sp" />
</androidx.appcompat.widget.Toolbar>
You're putting a TextView in your toolbar, but toolbars already have support for titles. Remove this textview, don't set anything on the textview, figure out how to change the toolbar !
private void setToolbarMethod() {
Toolbar toolbar = activityDisplayNoteBinding.toolbar.activityToolbar;
setSupportActionBar(toolbar);
}
this will now create your toolbar.
in your AndroidManifest.xml, you'll see something like this:
<activity
android:name=".foo"
android:label="some value" /> <-- you can change some value here to give the toolbar a default title.
Alternatively,
<androidx.appcompat.widget.Toolbar
app:title="foo"
android:id="@+id/activity_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/color_primary">
various different ways of setting the title, your problem is basically caused by having a TextView inside the toolbar for no reason
private void setNoteInActivity(NotesEntity notesEntity) {
try {
activityDisplayNoteBinding.titleTextView.setText(notesEntity.getTitle()); <-- this now becomes invalid, the text view is removed
activityDisplayNoteBinding.contentTextView.setText(notesEntity.getContent());
} catch (NullPointerException nullPointerException) { <-- side-note, this is terrible and probably not what you want to be doing, you should at least be printing the stack trace, calling finish will kill the entire activity without you or the user knowing what happened
finish();
}
}
you can use getSupportActionBar().setTitle("My Title");
instead