Using Room with Kotlin

If I was really exited to hear about Android Architecture Components in Google I/O 2017. In particular Room Persistence Library. I had pleasure talking with folks working on it in person during I/O! I want to try it for my own.

I had been using Kotlin prior to the I/O announcement. Having google fully commit it to as a first class citizen on Android was very encouraging.

In this post, I wanted to show how you can start using Room with Kotlin.

I started with a shell project with Dagger 2 setup. We will implement Room in Kotlin project using Dagger2, later will also integrate it with RxJava2.

I am going to use a simple “ToDoList” app, that allows users to add a Task in the application. So first off, lets include the library.

Including Room

In your build.gradle file, include the room dependency. (1.0.0-alpha1 was the latest version at the time of this writing)

Defining Entities

Let’s now create `Task` entity. For now we will make it simple with id, description and boolean flag to indicate if the task is completed.

If you notice, it is for the most part just a regular “data class“. We are just adding annotation for Room to make sense of it.

@Entity(tableName = “task”) as it denotes, is using the table name called “task”. If name is not specified, by default class name is used as the Table name.

@ColumnInfo annotation on  a field relating it to the column on the table. e.g. in this example you can see that on the db column name uses “_”.

@PrimaryKey(autoGenerate = true) is applied to “id” field. which in this case is autogenerated. An entity must have at least 1 PrimaryKey.

Defining Dao

Dao is where Room does its magic. We just need to define a interface along with the SQL queries. Room at compile time generates the actual implementation of this class for us to use. This may remind you of Retrofit, This is exactly what happening here.

As you can see, we have an interface which is annotated with @Dao, in there we can see multiple functions annotated with various other annotations.

Lets look at one of them, “fun getAllTasks(): List”, this function returns list of all tasks from the database. This function is annotated with @Query annotation. In there we have the sql query specified. This query is validated at compile time. If the query is malformed it will fail the build. With this you can feel confident that if it compiles, it will work.

Now let’s look at the little more complex one. “fun findTaskById(id: Long): Task”. This function is annotated with @Query(“select * from task where id = :p0”).

There is a currently a bug where kotlin converts the parameters to p0, arg0 etc. Hence, the query above specified “:p0”. Ideally we should be able to say “:id”. This will be fixed in the near future. Until then, pay close attention to compile errors to identify this type of mismatch.

Defining Database

We define our database by creating an abstract class that extends RoomDatabase.

Class is annotated with @Database which defines the all the entities(table) it contains, its version. If you look closely, “exportSchema” is set to false here. If you do not, it defaults to “true” which generates a compile time warning as you can see blow:

warning: Schema export directory is not provided to the annotation processor so we cannot export the schema. You can either provide `room.schemaLocation` annotation processor argument OR set exportSchema to false.

This is class pretty much like dagger component, this exposes Dao we defined above. Here we are exposing “TaskDao”

Configuring in Dagger

Like dagger, we will build the room database. Note, this is an expensive operation so, we would want a singleton object. Lets look at the configuration here:

We are building Room database using the application context, We point to the abstract class we defined above, database file name we want.

We are calling following function so that we can run queries in main thread.

.allowMainThreadQueries()

If we did not call this, we would see an exception indicating that we cannot access database on main thread.

Caused by: java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long periods of time.

In the later part we will be using RxJava and we will get rid of this. For now, lets move on. We are using Dagger to provide the TaskDao also.

Getting Entities in Presenter

In this example we are using MVP pattern. Lets see how we can get the entities and show it in a recycler view.

Thats it! At this point we are able to define Task entity, use Room to fetch the entities and display them on a Recycler view.

Using Room with RxJava/RxAndroid with Kotlin

Let’s take this up a notch by introducing RxJava/RxAndroid. Add the RxJava/RxAndroid dependency in our build file by adding the following.

compile "io.reactivex.rxjava2:rxjava:2.1.0"
compile "io.reactivex.rxjava2:rxandroid:2.0.1"

We would also need to add one more dependency

compile "android.arch.persistence.room:rxjava2:1.0.0-alpha1"

With this we can now start using Room with RxJava.
Let’s change our function that returned list of Task to return a Flowable.

 @Query("select * from task")
 fun getAllTasks(): Flowable<List<Task>>

With this we can now remove “allowMainThreadQueries()”. Our Module would simply do

<pre>@Provides fun providesAppDatabase(context: Context): AppDatabase =
Room.databaseBuilder(context, AppDatabase::class.java, "my-todo-db").build()

We will then need to modify our presenter to use the updated function. Here is the full presenter.

todolist

And that is it!, At this point you have Room, Dagger, RxJava all working together using Kotlin!

You can find completed sample at https://github.com/manijshrestha/ToDoList

Advertisements

Using Android Beam/NFC to transfer Data

Most of the Android devices have NFC reader built in. NFC can be used to transfer data between two devices, trigger actions on device etc.
In this post I am going to build a simple app that transfers data between two devices using NFC.

It is important to understand how NFC works. I am not going to explain those in detail as there are many resources on the internet that does a really good job of explaining the technology.

Goal of this post is to build a simple Android application that will send some text data over to another NFC capable Android Device. To test this you will need two android devices with NFC. You will need to deploy the application to both the devices.

So to enable NFC on you app, the very first thing you would need to do is setup permission in AndroidManifest.xml

Permissions

Add the following tag to the AndroidManifest.xml to access the NFC hardware.

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

Also add uses-feature tag to specify the feature used by the application. If the Application must have the NFC, you would want to add android:required=”true” attribute to it.

<uses-feature android:name="android.hardware.nfc" />

We would need to use SDK level 14+ to be able to use Android Beam. SDK level 9 has very limited support so you would want to use SDK level 10 at minimum for good NFC support.

<uses-sdk android:minSdkVersion="16"/>

Message Sender Activity

We will simply implement NfcAdapter.CreateNdefMessageCallback interface. This will require us to implement NdefMessage createNdefMessage(NfcEvent nfcEvent)
This method will be called when Android Beam is invoked. Here is the method implementation.

   @Override
    public NdefMessage createNdefMessage(NfcEvent nfcEvent) {
        String message = mEditText.getText().toString();
        NdefRecord ndefRecord = NdefRecord.createMime("text/plain", message.getBytes());
        NdefMessage ndefMessage = new NdefMessage(ndefRecord);
        return ndefMessage;
    }

In our onCreate method we need to get NfcAdapter and set the callback to this class. Here is the snippet.

.. ..
 @Override
    protected void onCreate(Bundle savedInstanceState) {
.. ..
       NfcAdapter mAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mAdapter == null) {
            mEditText.setText("Sorry this device does not have NFC.");
            return;
        }

        if (!mAdapter.isEnabled()) {
            Toast.makeText(this, "Please enable NFC via Settings.", Toast.LENGTH_LONG).show();
        }

        mAdapter.setNdefPushMessageCallback(this, this);
.. ..
    }
.. ..

So that’s all to it to be able to send a NFC NDEF message.

NFC Intent

Lets create another Activity that will be respond to the NDEF message and display the message.
In the activity we just need to inspect “Intent” and pull NDEF message.
In this demo we will name this activity as NFCDisplayActivity. We will check for the info onResume() as such

   @Override
    protected void onResume(){
        super.onResume();
        Intent intent = getIntent();
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
            Parcelable[] rawMessages = intent.getParcelableArrayExtra(
                    NfcAdapter.EXTRA_NDEF_MESSAGES);

            NdefMessage message = (NdefMessage) rawMessages[0]; // only one message transferred
            mTextView.setText(new String(message.getRecords()[0].getPayload()));

        } else
            mTextView.setText("Waiting for NDEF Message");

    }

Here we are verifying that, this activity was triggered by NDEF_DISCOVERED action. (There are 3 possible actions, NDEF_DISCOVERED, TECH_DISCOVERED and TAG_DISCOVERED)
We then extract the Parcelable extra message from the intent and put that in a text view.

You will need to configure this Activity in your AndroidManifest.xml like below

  <activity
            android:name=".NFCDisplayActivity"
            android:label="NFC Data Display">
            <intent-filter>
                <action android:name="android.nfc.action.NDEF_DISCOVERED" />
                <category android:name="android.intent.category.DEFAULT"/>
                <data android:mimeType="text/plain" />
            </intent-filter>
        </activity>

With that when NFC message comes with mimeType of “text/plain”, it will start our Display Activity.

You can find my the entire project in github https://github.com/manijshrestha/AndroidNFCDemo.

Here is the Video of the app.

Implementing Android Status bar notification in phonegap/cordova app.

This is a quick write up to demonstrate phonegap statusbar notification plugin in a cordova (formally phonegap) app.
I am going to run through steps for creating an android application utilizing phonegap.

Creating a Project
I am going to assume that you already have android SDK and Eclipse plugin installed. If not, please follow the developer guide to do so.
We will create an sample application, we are going to name it “phonegapstatusnotificationdemo”.

Importing Cordova
At this point we should have a sample android application. Now, we are going to import the cordova(phonegap) libraries in our application. At the time of this writing Cordova 2.2.0 is the latest version. You can download the library form their website.

After you download the zip file, open and locate “lib/android”, and extract the cordova-2.2.0.jar.

  • Place the jar file into “lib” folder in your Android project. This folder should already be in your class path. If not you may need to do it manually via project properties.
  • Also, find the “xml” folder in the zip file and place it under “res” folder in the android project. The xml folder contains the config.xml that has the phonegap configuration.
  • Create a folder named “www” inside “assets” folder in the android project as well.
  • Place the cordova-2.2.0.js file from the zip into the www folder you just created.

You are now set to use phonegap.

Updating the Activity
Since phonegap places the html as the view in the application, we have to do 2 things.
1. create the html file
2. Update the Activity to extend DroidGap and local the html from step 1.

We are going to do just that. Lets create a html file and place it in the “www” folder inside the “assets” folder in the android project.

  <html>
	<head>
		<script type="text/javascript" charset="utf-8" src="cordova-2.2.0.js"></script>
	</head>

	<body>
		Hello World!
	</body>

</html> 

In your main activity, update it to extend the DroidGap.

import org.apache.cordova.DroidGap;

import android.os.Bundle;

public class MainActivity extends DroidGap {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.loadUrl("file:///android_asset/www/index.html");
	}

}

Now you can run your phonegap application on your device or emulator. You should see the “Hello World” text on a blank screen.

Using Statusbar Notification plugin
Now, lets use a Status notification plugin. These steps will be same for implementing other phonegap plugins also.
Phonegap plugin work in 2 parts.
1. Javascript: Plugin will have a javascript code that your application can call form your html or js.
The provided js will invoke the back end java code. You shouldn’t need to worry much about the inner workings of the plugin js code. But it is import to understand the framework so you can debug issues.

2. Java code: This is the code that phonegap plugin framework will call when this method is called from the javascript library code.

Today we are going to use the statusbar notificaiton plugin.
Lets grab the plug in code from github.
https://github.com/phonegap/phonegap-plugins/tree/master/Android/StatusBarNotification

README provides steps to import this plugin in your application. We are going to do just that.

Importing Plugin files
place the “.java” files into your android project src package. At the time of this writing there are two files (StatusBarNotification.java and StatusNotificationIntent.java). Make sure you update the package appropriately. I would encourage to use the package name used in these java files for simplicity.

Now, place the statusbarnotification.js into your “www” folder. At this time you can include this script in your index.html by placing the html below in the portion of the html

<script type="text/javascript" charset="utf-8" src="statusbarnotification.js"></script> 

In your res/xml/config.xml file, place the following script inside the section.

<plugin name="StatusBarNotification" value="com.phonegap.plugins.statusBarNotification.StatusBarNotification"/>

If you had placed the java files above in different package structure, be sure to change the value filed to appropriate location.
Since phonegap provides a default icons for notification, which is used in the java code, you will have to copy the png files from the plugin into your res/drawable folder. If you want different icon, just be sure to have those icons in the folder and change the reference in the java file. (Watch for “int icon = R.drawable.notification;” references, in StatusNotificationIntent.java)

So in your html file, whenever you want to show a notification, you can call the following javascript function.

window.plugins.statusBarNotification.notify("Put your title here", "Put your sticky message here");

.

You can checkout out my sample application on github (https://github.com/manijshrestha/PhonegapStatusNotificationDemo) that uses this plugin. If you have any questions/ enhancement request to this plugin feel free to PM me.

Thank you,

Decompiling an Android apk file to view the underlying code

Few weeks ago, I saw a question posted on linkedin Android group, asking if we can view the application code of a complied apk file. There were interesting responses stating it is possible. Today I am putting it all together in this post about how you can do just that.

1. Obtaining the “apk” file: There are many ways that you can obtain the apk file. You can probably find it on the Internet. Or the best way is to get it from your phone. In this example, we will tear apart facebook android app 🙂

The apk file of the application that is purchased from the android market is stored in ‘/data/app’ folder on your phone. To access this directory, you need super-user access.  If your phone is rooted, follow the steps below to obtain the apk file if not, you might be able to get one from the Internet.

$ ./adb shell
$  su
#  cd  /data/app
# ls com.facebook*
# com.facebook.katana-2.apk
# cp com.facebook.katana-2.apk /sdcard
#

Copy over the apk file on to your computer from the sdcard.

2. Obtaining the “.dex” file: Open the downloaded apk file as a zip file. You can use “Archive Manger” on linux or “WinZip” on windows. You can also change the file extension to “.zip” and have the OS automatically open it as a zip file.

In there, you should see “classes.dex” file. This is the byte code of the complied application. Extract the file on to your computer.

3. Dex2Jar tool: You need dex2jar tool to decode the dex file to a jar file. The dex file is the Dalvik executable file. You can get the latest and greatest version at

http://code.google.com/p/dex2jar/downloads/list.

Download and install the application in your computer. I extracted it out on my android installation folder.

Once you have it run the “dex2jar” command to decompile the “.dex” file extracted in step 2.

You can run the following command on linux, on windows you can run the “dex2jar.bat” instead of “dex2jar.sh”


$ ./dex2jar.sh classes.dex

You should see an output as follows.

4. Decompiling the jar: You can now open the decoded “.jar” file from step 3 on a java decompiler of your choice.

There are few out there. I choose JD-GUI. You can download one from their site at: http://java.decompiler.free.fr/?q=jdgui

Install the tool and open the jar extracted on step 3. Boom now you can see the application code!