Press ESC to close

In this lesson we will see how to create our android studio as well as firebase app. Then we will add the firebase app to android studio. We will see two techniques of creating and adding the firebase app to android studio. Then we will also see the libraries we will use in the app we are building.

Note that this lesson is part of an Android Firebase Realtime Database CRUD course we are currently covering. In the course we are creating a full Android app, powered by Firebase realtime database that supports:

Our main androidx appcompat library which will give us access to appcompatactivity as well as other classes.

2.

RecyclerView

Androidx recyclerview to give us the adapterview we will use to render our Firebase data.

3.

CardView

To represent a single recyclerview row or item.The recyclerview will thus comprise several cardviews. Moreover we use cardviews in our dashboard screen, in our detail activity and in our crud activity.

Above you can see we have added our google-services classpath. Please don’t forget it. You may use later versions of it.

Lesson 2: Model Class

A Model class is a data object or business object class. It defines the entity we want to work with as the core of what our application is about. For example in this case we are creating Scientists CRUD App. This means we will adding,updating, reading and deleting Scientist objects to and from our Firebase Realtime Database. Thus our model class will Scientist class.

NOTE/= This class is part of a multi-episode course on Firebase CRUD. In the course we are developing a full android application with full CRUD capability.

That class will define properties for a single Scientist. And we obtain that single scientist by instantiating that class. The only requirement of our model class for it to be readable by Firebase is that it should have atleats an empty constructor. By readable by Firebase we mean that we will pass that class’s instance to Firebase’s setValue() method to save our data.

For example consider the below example:

mDatabaseRef.child("Scientists").push().setValue(scientist)

In the above code we are passing a whole Scientist object to the setValue() method to be persisted in Firebase . The class defining that scientist must have an empty constructor.

That interface is called a marker interface, thus we don’t need to implement any method. Serializable interface will allow the instance of our Scientist class to be serializable and deseriable. We will need to do serialize it so that we can pass a whole object across activities. Then in the target activity we can deserialize it and render its fields.

Step 3: Create An Empty Constructor

public Scientist() {
//empty constructor needed
}

As we had said earlier , you need to provide an empty construcor to our model class. If you needed to make injections into your class via the constructor then you can create a seperate constructor to do that. See for example how we’ve created one:

The special thing about them is the @Exclude annotation. This annotation is provided to us by the com.google.firebase.database annotation we had included in our imports. It is telling Firebase to ignore generating the key node while persisting our data. We have to do this because Firebase will be generating that key automatically. In fact we’ll simply use the two methods to get and set that key locally but we won’t be persisting it.

Conclusion

We have created our model class. This simple class is at the center of our application because it defines the central entity we are working with. It is this class’s instance that will be persisted, read and deleted. We’ve talked about constructors for the class, the fields as well as public accessor methods.

Now move over to the next class.

Lesson 3 : Utility Methods and App Class

In this lesson we are creating two important methods. The first method is our app class. The second is the Utils class. This lesson is part of the android firebase realtime database crud full app development course we are currently covering. In the course we see how to create a full project from scratch based on Firebase Realtime database and supporting all CRUD operations.

Objectives of this Lesson

Here are the objectives of this lesson:

Create utility methods that will be needed throughout the project.

Load a custom font into our android app across all activities.

(a). App.java

The role of this class is simple: Load custom font into our app. We will use a library we had earlier on added in our dependecies: Calligraphy.

(b). Utils.java

This class as we said is to contain our utility methods. It is best practice ton confine methods usable across the whole app in one simple class from which they can be called. Such methods are normally made static so that we don’t need to every now and then instantiate them to invoke our methods.

Step 1: Create the Class

public class Utils {

Step 2: Show Toast message

This method will allow us show toast messages throughout various activities.

Lesson 4: ClientSide Search/Filter of Firebase Data

In this lesson we will learn how to filter Firebase data on the clientside. Clientside filtering is an in-memory search filter. This means we hold our data in a data structure like an arraylist and then filter from there.

NOTE/= This class is part of multi-series course we are doing right here at Camposha about FirebaseCRUD. See the course contents on the sidebar.

This is a very fast search because we don’t need to make any connections to the database or online server. However this type of search is only suitable for small datasets. You don’t want to be holding tens or thousands of rows of data statically throughout the lifetime of your app.

In that type of scenario you would need to perform a server side search.

How our search will work.

We download Firebase Data once the first time the user visits our Listing page.

We hold the data statically. Rather than holding it as an instance field,we hold it as a class member. Thus the list is not garbage collected.

As you can see we have provided the necessary imports including our MyAdapter as well as our model class. The class is extending the Filter class, which is abstract. Thus we will be required to override two classes we will talk about in a short while.

Step 2 : Define our Class members

static List<Scientist> currentList;
static MyAdapter adapter;

We then create two class members:

currentList – The current list that should be filtered.

adapter – The adapter instance which will be used for two purposes. First to pass our search results back to the MyAdapter class and secondly to the MyAdapter classes of changes in our dataset.

Step 3 : Perform our Actual Filtering

We now come and override the first of the two methods we promised. That method is the performFiltering() method. It will take one parameter:

constraint – A CharSequence representing our search term or constraint.

The lesson is part of a full project course. Please follow the course to see its usage, specifically our MyAdapter and ScientistsActivity classes.

Conclusion

We have seen how to perform a search and filtering agains Firebase data. And we’ve said it is a client side search. This means we obtain all our data and hold statically and search against it. This means our search is fast but suitable for small datasets.

Now move over to the next lesson in this series.

Lesson 5 : RecyclerView Adapter

Our RecyclerView Adapter

It is time to come create our adapter class. This class is important since it allows us inflate custom views and bind data to them once it is applied to our recyclerview.

NOTE/= This lesson is part of a multi-episode on Firebase CRUD Full App Development Course. In the free course we are creating a full application with Firebase Realtime database backend.

Step 2: Define Instance Fields

You can see we are defining objects and data types that will allow us hold different values. The Context object will allow us hold the received Context object. The background will represent our material letter icon background while the mMaterialColors is an array that will hold for us the different material colors we will load from color resource file.

The scientists list will hold the list of all scientists received via the constructor. The filterList will hold the filter results that need to be displayed in our recyclerview.

Step 3: Define our ItemClickListener

It’s just an interface containing an abstract method that will be our event handler:

interface ItemClickListener {
void onItemClick(int pos);
}

Step 4: Create our ViewHolder class.

We are creating it as an inner class, meaning it’s contained in our MyAdapter class:

We’ve used the LayoutInflater class to inflate the model layout into a view object. We’ve then set the the background color of that view object using the setBackgroundResource() method, passing in our background integer. We’ve then returned that ViewHolder’s instance, passing in the inflated view object to the constructor.

You can see above that we obtaining the properties of our scientist object and binding them to their respective textviews. As for the material letter icon we are setting it a random background color. The letter icons will be obtained from the name.

Now to set an alternating row background colors to our recyclerview all we need is the following code:

Step 9: Listening to RecyclerView Click Events

The above code listens to click events for our recyclerview item and and invokes a method called sendScientistToActivity() from our Utils class. We are opening a detail activity, in the process passing along the clicked Scientist object. We’ve used lambda expression above which requires Java8 enabled.

Also, return the number of scientists that will be bound to the recyclerview:

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

Step 10: Return a Filter object

In the above code we are returning a Filter instance. Filter is an abstract class defined in the android.widget package that allows us perform filtering and publish results. The above method is being overriden since earlier on we had implemented the Filterable interface.

We are returning a FilterHelper instance since our FilterHelper class is inheriting from the android.widget.Filter class.

FULL CODE

(a). /Data/MyAdapter.java
Our MyAdapter class is contained in the Data package of our project.
Here is the full code:

Lesson 6 : CRUD Helper – ADD READ UPDATE DELETE

ADD READ UPDATE DELETE

In this lesson we will write re-usable methods that will allow us to perform full CRUD operations against Firebase Realtime Database. Firebase Realtime Database we had said is a cloud-based realtime database by Google that allows us to store text content in json format.

The stored data can then be synced across different devices. To work with any database or storage service, you need to be able to perform CRUD. CRUD stands for:

C – Create or Insert.

R – Read or Select.

U – Update or Edit

D – Delete or Remove

These are the basic operations you need to work on any data. And normally these are the operations you need to create a full application like we are doing in this course.

NOTE/= This lesson is part of our Android Firebase Full CRUD course. We recommend you take the full course, it’s free. However you can still follow and use the code here without taking the course.

Why CRUD?

CRUD we have said stands for Create Read Update and Delete. We need to do these because they are what you need to create a full application. You will always need to persist your data in a database, read that data, update it when necessary and delete it when not required.

Why Firebase Realtime Database

Firebase Realtime Database is Google’s flagship cloud-based database. Firebase realtime database allows us save data in the cloud and sync the data across a variety of devices, no matter the platform.

It also offers offline capability, persisting data on the disk thus we don’t haven’t to connected at all times to view our data.

What We are doing

In this lesson we will write instance methods that will allow us perform CRUD operations. The methods once defined can be called from anywhere within our app. The only requirement is that we pass the appropriate parameters.

Writing methods in a seperate class provides us with re-usability thus avoiding duplications throughout our app.

We have invoked the child() method of our FirebaseDatabase instance. In that method we have passed Scientists, think of this as the name of the json node that will store our scientists. Or think of it as our table name. Then we invoke the push() method which is responsible for pushing our data and returning a key. We have also invoked thesetValue(). Thie is the method that sets the data that we want to push to Firebase Realtime database. We have passed a full object. The only requirement for that object to be processed by Firebase is to have an empty constructor. Firebase will generate fields based on the properties of the data object.

Obviously we need to follow the progress of the operation. Thus we add a completion listener event handler. This will tell us when the operation is complete so that we can react to our result. In this case we hide our progressbar. Then we check if the task was successful using the isSuccessful() method. if we were successful we open a listing activity where our data will be loaded. If we encountered a failure we will show a dialog with the exception message. That exception we get it from the getException() of our Task class. We show it’s message by invoking the getMessage() method.

Step 2: How to read/select/retrieve From Firebase

In the second step we see how to read or select data from Firebase Realtime database. So we define the method:

You can see we are passing in an annonymous class to our ValueEventListener. Then we override the onDataChange which gets raised when our data changes. The onDataChange method takes in a DataSnapshot object which gives us a snapshot of our data. Now all we need to do is to work with that DataSnapshot.

However first we are going to clear our memory cache:

DataCache.clear();

That DataCache object will be our memory cache. Basically it will cache our data in memory throughout the lifetime of our application. Thus we don’t need to make calls to our Firebase realtime database every now and then unless we want for example when we make an edit. However be aware that Firebase Realtime database also provides a simple caching of our data offline. However we have no control of that cache. For example we are not able to search it without making calls to the cloud. That’s why we have our DataCache. All our searches will be against this DataCache, which is simply an ArrayList object.

Once our cache has been cleared we will check if we have any data in our DataSnapshot:

Step 3: How to Update/Edit Firebase Data

Let’s now come and see how we can update Firebase Realtime Database data. Update means you already have an existing data and you want to make changes. The important part for you to be able to update is to have the key for the node you want to update. Say you want to update a Scientist object, well you need to have the key for that scientist. Well but how do get that key?

You need to retrieve that key when fetching/reading/selecting your data. If you go back to the previous step where we were selecting data you will see that we were getting our key from our DataSnaptsshot object. Here’s how we did it:

You can see the ds.getKey() which is giving us a key object that then we attach to our Scientist object. So when designing your model class you need to accomodate a key field. However in your accessor methods you make sure you exclude it from being sent to Firebase:

Look at what we’ve done. First we’ve referenced the node to be updated which is our Scientists node. This will contain a list of scientists. Then we’ve invoked another child() method. This now gives us a particular scientist provided we supply the key as we’ve done. Then we simply invoke the setValue() method,passing in the updated scientist object.

As usual we are listening to completion then checking for success of the task using the isSuccessful() method.

That’s it we’ve updated our data.

Step 4: How to delete/remove Firebase Data

Let’s now come and see how to delete Firebase Realtime data. Deleting is important because it allows you to free up space for more objects. Again, the most important step in deletion is to have a key for the scientist you intend to delete. Without that key you won’t know which node to delete.

We’ve referenced our root node containing all our Scientists. Then passed the key to identify the one we want to delete. To delete it we simply call the removeValue() method. We then listen to completion events and react to them appropriately.

Conclusion

We have seen how perform all the CRUD operations in Firebase Realtime Database. We’ve said the code has been written as part of a full app development free course that you can take. However we’ve also said that you can incorportate the above code easily in your code. All you need do is copy it into your project, then invoke the method you want and pass it the required parameters.

Now proceed to the next lesson.

Lesson 7 : Splash and Dashboard Activities

In this lesson we want to create our splash and dashboard activities. These will represent two screens that make our application more professional. The splash screen will allow our us display our logo, title and subtitle for our application or company. You can change the time taken to display the splash screen or remove it entirely from the project. Splash screen is not all mandatory for this project.

On the other hadn our dashboard activity is vital for our project. It gives our application a centralized location from which we can navgate our app. It will contain cardviews that can lead us to other parts of the application.

NOTE/= This lesson is part of android firebase crud course we are currently covering. We advise that you take the full course to see how to properly apply this lesson in the whole app. The course is free.

What We are Creating

We will create three files:

No.

File

Role

1.

SplashActivity.java

Contain our java code for a splash screen.

2.

DashboardActivity.java

Contain our java code for dashboard activity

3.

activity_splash.xml

Contain XML Code for our Splash Screen.

4.

activity_dashboard.xml

Contain XML Code for our Dashboard Screen .

5.

top_to_bottom.xml

Will be contained in an anim folder. Will contain our animation code for moving a widget from a top position to sliightly lower position.

6.

fade_in.xml

Will be contained in our anim folder. Will contain our animation code for fading in a widget.

How our Splash Screen Works

User clicks the app icon in his android device.

The application starts.

The launcher activity is our slash activity, thus it is started first.

We dop our logo imageview using the top_to_bottom animation.

Then we fade in our main title and sub title textviews.

We then sleep a thread for like 2 seconds.

Then we open our dashboard activity.

We kill the splash activity.

How our Dashboard Screen works.

It is opened by the splash activity.

It makes us of a CollapsingToolbar and has an image set to it.

It contains 4 cardviews.

When the View All cardview is clicked we open the activity for viewing all our scientists in a recyclerview.

When the Add New cardview is clicked we open the activity for adding or registering a new scientist activity.

When the Another Item cardview is clicked we open a material lovely dialog.

When the exit button is clicked we finish the current activity, thus stopping our application.

Video Lesson

Step 1: Create Splash Animations

(a). top_to_bottom.xml

This animation, as we had said earlier will drop our imageview from a higher position to a lower position.

Under your res directory, create a folder called anim. This anim will contain our animations.

Lesson 8 : Activity for Adding,Updating and Deleting

In this lesson we want to explore our CRUDActivity. This activity will be re-used for three purposes. First it will allow us register or post a new scientist to Firebase Realtime Database. Secondly it will allow us update existing scientist object. Thirdly it will allow us delete a scientist object.

NOTE /= This lesson is part of a multi-episode free course on perform CRUD operations against Firebase Realtime Database, in the process creating a full application.

This lesson involves us:

Creating our CRUD Activity as well as its corresponding activity_crud.xml.

Creating two menu resource files: first one shown when we open our CRUD Activity for the sake of adding a new scientist. Secondly shown when we open our CRUD activity for sake of editing or deleting Firebase data.

Invoke CRUD methods defined in the FirebaseCRUDHelper. Those methods will allow us to update as well delete our data.

How our CRUD Activity Works

User clicks the ‘Add New’ card in the Dashboard or Add New menu item in the scientists activity.

The CRUD Activity is opened.

A null scientist object is passed in the process.

Because null is passed we inflate add_new_item_menu.xml as opposed to edit_item_menu.xml in our toolbar as a menu item.

The add_new_item_menu.xml will have a menu item that when clicked posts or inserts our data to Firebase Realtime database.

The data being inserted will be typed in the edittexts in the page.

The data will first be validated by a method we had earlier defined in the Utils class.

If data insert fails, an error message is shown to the user in a cardview within the same activity.

If the data insert succeeds, the CRUDActivity is closed, and the ScientistsActivity is opened where recyclerview is scrolled down to the last added item.

If the user clicks a recyclerview item, the detail page is opened.

If the user clicks the edit button or edit menu item, the CRUDActivity is opened.

This time the scientist whose details were being shown is passed along.

Because a scientist object is being passed, our CRUDActivity will know that it’s opened for the sake of editing or deleting.

Thus the edit_item_menu.xml is inflated as the menu resource file as opposed to the add_new_item_menu.xml.

That edit_item_menu.xml will have menu items for updating as well as deleting, shown as icons.

The user types the data and clicks update button.

Our Firebase data is updated.

If an error occurs, the error is shown in a cardview within the same page.

If the update is successful, the CRUD Activity is finished, and the Scientists activity is opened.

If the user clicks, the delete button, data is deleted and the scientists activity is opened.

Video Lesson

Step 1: Create New Item Menu

Under the res directory, create a folder called menu.
Inside it create an xml file called: new_item_menu:

Those instance fields include our edittexts and datetimepicker for entering our data, our progressbar for showing progress and texview for showing header title. Moreover we have a Scientist object which will hold the scientist that is passed along for editing. We also have a FirebaseCRUDHelper instance which will allow us to invoke methods that contain logic for performing CRUD. We also have a database reference which will be passed along.

Lesson 9 : Firebase RecyclerView and Detail Activities

In this lesson we will explore two important activities, listing or recyclerview activity as well as the Detail Activities. These are data rendering activities. They allow us show our Firebase data to the user. The recyclerview activity will render a list of firebase data using recyclerview. The detail activity will show the details for a single item. It will be shown when a single recyclerview item is clicked.

NOTE/= This lesson is part of a multi-series course we are currently covering on Firebase Realtime Database CRUD. In the course we are seing how to develop a full android application based on Firebase Realtime Database. The full app will support adding of data, fetching of data, updating of data as well as deleting data.

How our RecyclerView Activity works.

We are working with Scientist as our data object. The RecyclerView activity is our listing activity. It will be called the ScientistsActivity. It’s role is display data fetched from Firebase Realtime database in a recyclerview. The recyclerview will have alternating background colors.

The recyclerview will work with the adapter which is responsible for binding data to it as well as inflating our custom layout. The adapter will be set to the recyclerview using the setAdapter() method.

Every row in the recyclerview will comprise:

MaterialLetter Icon – To display letter icons extracted from name.

TextViews – To display name, description and galaxy of the scientist.

When a recyclerview row is clicked, we will open the detail activity, passing along the clicked scientist object.

The recyclerview shall be searchable via the toolbar. We will render a toolbar searchview which will allow our users to search filter our firebase data. The search and filter will be disconnected and offline.

How the Detail Activity works

The detail activity is a static activity in that it doesn’t do any processing or make any calls to Firebase. Instead it only renders the detail for our Scientist object. It is very important however because it provides us with a way of showing the user individual details of our scientist object without giving the user capability to edit.

However if the user intends to edit then he can click a button or menu item and move to the editing page.

The detail activity will be have some of the following components:

CollapsingToolBar

Floating ActionButton

CardViews

TextViews etc

Video Lesson

Step 1: Create Detail Activity Layout

(a). activity_detail.xml

This is the layout that will be inflated into our Detail Activity. It will content another layout called detail_content.xml. Here is the code for the activity_detail.xml:

Among them as you can see above are LinearLayoutManager and DividerItemDecoration. We set the LinearLayoutManager to our recyclerview using the setLayoutManager method and DividerItemDecoration using the addItemDecoration method.

Then to download and bind downloaded data to our recyclerview all we need is the following method:

The onQueryTextChange. The above callback is invoked when a user types in our searchview. The first thing we will do is set the query to a searchString variable. That allows us hold the query in a public variable that we will be able to invoke from anywhere including the MyAdapter class.

We then instantiate our MyAdapter passing in the Context as well as the DataCache. That DataCache is an arraylist that will cache our data in memory. We will be performing our search and filter against that arraylist.

Take note that we are also passing in the query to filter method. That query will find its way in our FilterHelper class where we are performing our actual filtering.

Finishig Up

Well we have finished the most important steps by this lesson. However we are yet to view our AndroidManifest. This file is important because we need to register our components right here as well as add the necessary permissions.

AndroidManifest.xml

This file is mandatory to android development. It is autogenerated by android studio and normally if you don’t add other activities in your project or require any special permission then you don’t have to touch. By default android studio registers the generated MainActivity file.

However in our case we will need to modify this project.

(a). Add Internet Connectivity Permission

You need internet connectivity permission for your app to be able to access internet from the users device.

<uses-permission android:name="android.permission.INTERNET"/>

(b). Register Activities

Activities are android components and have to be registered like any other android component.

Share Article:

Tags:

When I was a 2nd year Software Engineering student, I buillt a now defunct online tool called Camposha(from Campus Share) using my then favorite language C#(ASP.NET) to compete OLX in my country(Kenya). The idea was to target campus students in Kenya. I got a few hundred signups but competing OLX proved too daunting. I decided to focus on my studies, learning other languages like Java,Python,Kotlin etc while meanwhile publishing tutorials at my YouTube Channel ProgrammingWizards TV which led to this site(camposha.info). Say hello or post me a suggestion: oclemmi@gmail.com .
Follow me below;
Github
, and on my channel:
ProgrammingWizards TV

December 14, 2019

Flutter Load More Pagination Examples

December 15, 2019

Android TabLayout with Examples

2 Comments

Mbabazion May 4, 2020

Hello!
Thanks for these wonderful projects am having a problem with importing these