Android Development Guide for the Internet of Things enthusiasts — II

Darren Mistry
7 min readMay 6, 2018

--

Hello again…! Previously we talked about how to create a new android and Firebase project and add authentication to your android app. In this tutorial, we are going to talk about how to store and load data from the cloud using Firebase real-time database on our android apps. Refer part 1 here.

Firebase Database:

Databases offered by Firebase

Firebase offers two kinds of databases: Realtime Database and Cloud Firestore (Beta). Here we will use the Realtime Database. Click on the Database option in the Navigation menu. Select Realtime Database.

Locked mode and test mode

You will be prompted to select security rules. For our purpose, we will start in test mode.

Click on the Rules tab.

Setting rules for database

If you want only authenticated users to read/write from your database, set

{
“rules”: {
“.read”: “auth!=null”,
“.write”: “auth!=null”
}
}

Once you have modified your rules, click on Publish to commit your changes.
Firebase Real-time Database is a NoSQL database. Here there are no tables, relationships, SQL queries. Data is stored in JSON format. One can access a data node by using its path in the JSON tree. You can store various kinds of data like String, float, int, boolean. You don’t need to specify the type while writing data in the console. Firebase automatically detects the datatype of your data.

In this tutorial, we will be displaying temperature and pressure on our app. This data can be collected from a BMP180 sensor and stored in the database.

Click on the plus sign to add a node

Click on the plus sign to add a node. This will show a property-value pair. If you want to have a child node, enter a name and again click on plus. This will create a child node. At the last step, add a name-value pair to specify the end of your hierarchy.

Click on add

So here if I want to read the value “i am child”, my path will be “/parent/child”. There is no limit on the hierarchy level. However, it is a good practice to keep your data structured and non-redundant. To delete a node, click on the “cross” symbol near the plus symbol. This will delete the node with all of its children. Create a structure like below:

Database structure

Here the key “ I0k23Y6rhBfKwEaXjAEhqpq4htl2” is the user UID of the user we created earlier using our app. You can find it under the Authentication tab. There are two children: “temperature” and “pressure”. UID is a unique key assigned to each user by Firebase. The goal of keeping UID as a key is to store data of multiple users in a single database without getting overwritten or deleted by another user.

We don’t need to make such a structure for every registered user because Firebase creates a node location when we specify a write request at a non-existent node.

Now go to your android studio. Click on Tools -> Firebase. On the right side, you can see Assistant Pane. Under Realtime Database, click on Save and retrieve data to set up libraries and get code structure. For more information, go to https://firebase.google.com/docs/database/.

Add the Realtime Database dependencies

Since we have already connected our app to firebase, we need not do it again. Click on Add the Realtime Database to your app button to add the Realtime database dependencies automatically to your gradle files.

Create a new activity WeatherActivity to show the temperature and pressure from the database in the app. Here we will add Text views to display the data fetched. Text views don’t allow user input, unlike edit texts. We will also add a logout button for the user to log out of the app which will then lead to the LoginActivity.

Right on the folder just above the LoginActivity and select New — > Activity — >Empty Activity

Name the activity as WeatherActivity. Copy the following code in activity_weather.xml.

Some of the important classes and methods to be kept in mind for using firebase realtime database:

FirebaseDatabase.getInstance() — returns an instance of the database associated with the project. This instance can be used to read and write data at various locations.

FirebaseDatabase.getInstance().getReference(path) — returns a reference to the specified path in the database structure.

DatabaseReference -> addValueEventListener() — adds a listener that listens to data changes happening at the referenced location. The listener contains an onDataChange(DataSnapshot ds) method which fires up when data change/insertion/deletion takes place.

DatabaseReference -> addListenerForSingleValueEvent() — adds a listener but it fires up only once.

DatabaseReference -> removeEventListener() — removes a listener associated.

DatabaseReference -> removeValue() — removes the value at that reference.

DatabaseReference -> setValue() — adds/updates the value at that location.

DatabaseReference -> child(String s) — references to a child node with name equal to s. getKey() — returns the key of the reference.

DatabaseReference -> push() — pushes the data passed in parameters as a child of the reference. Generates a random key of the child.

DatabaseReference -> equalTo(), startAt(), endAt(),limitToFirst(int i),limitToLast(int i),orderByChild(String s),orderByKey() — query methods.

DataSnapshot — is the snapshot of the particular reference at that time instant. getKey() returns the key of the location and getValue(Object.class) returns the value of type Object. The parameter of getValue() can be changed as per the data stored at that location.

addAuthStateListener() — adds a listener to the FirebaseAuth object which fires up onAuthStateChanged() whenever a user logs in/out or the current user changes.

Tip: It is a good practice to define path names as a constant inside another Java class. This reduces program errors which are caused by simple typos in path names/key names. Here I have defined the key names in a class Constants.java inside a package named data.

Constants.java class inside data package

Our WeatherActivity.java will look something like this:

Here we have added the FirebaseAuth object to get information of the current user. If the FirebaseUser object is null, it means no user has signed in. We use finish() to terminate the activity. This is useful in cases where you want to allow both registered and unregistered users on your app but provide some functionalities only to registered users. Here we store the logged in user’s UID in Constants.java class to use it as a path.

Now we will need to redirect a user from the LoginActivity when he logs in to our WeatherActivity. For that, we will use startActivity() method. It takes an object of Intent class as a parameter. Think of intents as messages which are passed between activities of the same or different apps. For more details, look up here.

Modify the onClick() method inside loginBtn inLoginActivity.java.

Now run the app. If you run into any problems, you can always find the problem in Logcat. There are six modes: Verbose, Debug, Info, Warn, Error, Asset. For e.g to print in Verbose mode, use Log.v(“key”,“statement”). Modify the values from firebase console and observe the changes.

Now we will modify the launcher icon for our app. Right click on app->New->Image asset.

Setting foreground icon

Select an image/clip art/text of your choice for the foreground. Go to the background layer and set a color of your wish.

Setting background color

Click on Next and then Finish to modify the launcher icon.

Once we have created an app, we need to distribute it to our users. Just like there are .exe files for software in Windows and Linux, in Android, we have .apk files. There are two types of apk — debug apk and release(signed) apk. The apk which we were generating till now by running our app was a debug apk. It can’t be used to install the application on other devices. For that, we will have to generate a signed apk.

Go to Build->Generate Signed APK.

Generating signed apk

Click on Create new… to create a new keystore path.

Creating new key store

Enter the path you want to with the file name. Notice the extension of the file .jks. Fill in the other details and click on OK.

After generating new key store or using existing one

Click on Next.

Click Finish

After some time, you will a dialog at the bottom asking you to locate the apk. Click on that to open the folder containing apk in your File Explorer. Change the name accordingly and share the apk with your potential users.

locate your app

Full code : https://github.com/Death14Stroke/iot-android-demo

You can find the apk under Iotapplication/app/release/app-release.apk.

So dear readers, here you have created your first Android app using Firebase authentication and database. You can create more complex apps too by reading the firebase docs. In future, I will be talking about more UI based concepts for android. Till then, keep practicing!

--

--

Darren Mistry

Android developer by day, Gujarati shayri writer by night. DA-IICTian. Oracle.