Typesafe Activator

Agile Android with scala Example

Agile Android with scala Example

luismfonseca
Source
May 31, 2014
android scala agile

A quick example and tour that tells how to program in Android with scala, using agile-scala-android tool.

How to get "Agile Android with scala Example" on your computer

There are several ways to get this template.

Option 1: Choose agile-scala-android-example in the Typesafe Activator UI.

Already have Typesafe Activator (get it here)? Launch the UI then search for agile-scala-android-example in the list of templates.

Option 2: Download the agile-scala-android-example project as a zip archive

If you haven't installed Activator, you can get the code by downloading the template bundle for agile-scala-android-example.

  1. Download the Template Bundle for "Agile Android with scala Example"
  2. Extract the downloaded zip file to your system
  3. The bundle includes a small bootstrap script that can start Activator. To start Typesafe Activator's UI:

    In your File Explorer, navigate into the directory that the template was extracted to, right-click on the file named "activator.bat", then select "Open", and if prompted with a warning, click to continue:

    Or from a command line:

     C:\Users\typesafe\agile-scala-android-example> activator ui 
    This will start Typesafe Activator and open this template in your browser.

Option 3: Create a agile-scala-android-example project from the command line

If you have Typesafe Activator, use its command line mode to create a new project from this template. Type activator new PROJECTNAME agile-scala-android-example on the command line.

Option 4: View the template source

The creator of this template maintains it at https://github.com/luismfonseca/agile-scala-android-example#master.

Option 5: Preview the tutorial below

We've included the text of this template's tutorial below, but it may work better if you view it inside Activator on your computer. Activator tutorials are often designed to be interactive.

Preview the tutorial

Getting started

Hi.

Before compiling this example, you have to install SBT, the Android SDK and the Agile Scala Android SBT plugin.

The Agile Scala Android plugin should be installed with a global scope, in order to quickly start making new projects. If you don't wish this feature, you may skip its instalation and just add it as a dependency on each project.

If this example doesn't compile within the Activator, you may have to configure an Android target manually in its directory. Available Android targets can be listed by issuing the following command:

$ android list targets

Then, you can pick up one for this project with :

$ android update project -p . -t <target>

After that, you can connect your phone or launch an emulator, and run this example by executing :

$ sbt android:run

More information is avaliable on pfn's Android SDK plugin for SBT.

New (Scala) Project Android

This command allows you to create an Android project on the current folder, ready to be compiled and run.

npa <android package> <sdk version>

This very project was created with the following command:

npa pt.pimentelfonseca.activatorexample 19

This created a brand new Android project, targetting the versin 19 of the SDK, with pt.pimentelfoseca.activatorexample as the main package. We can have a closer look at the following:

  • An appropriate folder structure was created, alogn with the required Android files.
  • build.sbt

    This contains the project configurations and dependencies libraries: scaloid, gson and slick.

  • plugins.sbt

    This contains the project SBT plugin dependencies libraries: the agile-scala-android and android-sdk-plugin.

  • src/main/AndroidManifest.xml

    A minimalistic manifest file with the specified minimum Sdk version, and application entry point to launch the activity MainActivity.

  • src/(...)/ui/MainActivity.scala

    This is the activity referenced in the manifest file. It will just load the layout when being created.

  • .gitignore

    This file was also generated to simplify git versioning.

If this sounds familiar to you with the np SBT plugin - great. This task is remarkably similiar to np's, only for android projects.

After you've created a new project, a full SBT reload is necessary. This allows SBT to load the new build definitions and plugins dependencies. Since this template is already the result of npa, you can already experiment it by doing a run.

Creating a new Model

The next logical step after creating a new application is defining the bussiness models that it will work with. For this purpose, there's an auxiliar command that manages this, in a very similiar way that Ruby on Rails. The command is the following:

generate <Model Name> <attributes>
The attributes are a tuple of name with type. For example, the following commands creates a new model called Post, with title, number of views, and date as their attributes.
generate Post title:String numberOfViews:Int date:Date

Please use camel-casing when naming the variables as it will be important for other commands.

At this point, I want you to open a console at the project root, start SBT, and execute this command yourself. After this, the following file was generated:

src/main/scala/pt/pimentelfonseca/activatorexample/models/Post.scala

This is a simple Scala case class, and you can edit it and expand it further.

Every generated model will have a database mapping that is automatically generated. This feature will be explained in the next section.

Database

You can request an automagical conversion of your models into a relation SQL database with Slick as the backend. To do this, run the command:

migrateDatabase

This will compile your project, and use reflection to figure out the models fields. Then it will generate the necessary tables and helper methods to create a database. You can access the database anywhere in your application.

For example, to get the list of all Posts you can simply type:

App.posts

You can extend the tables using the Data Access Object pattern. So in this case, you can go to src/(...)db/dao/Posts.scala and write extra logic for the table.

Automatic Android Permission resolution

A basic Android application has no permissions associated with it by defult, meaning it cannot do anything that would adversely impact the user experience or any data on the device. This means to access common resources such as GPS, Camera, Internet, a permission needs to be added to the manifest.

Usually, only at run time will an error message inform the developer about the missing permission. To solve this problem, the Agile Scala Android plugin analyzes the source code and adds known missing permissions automatically.

Let's test this feature now:

  1. Open the MainActivity.

  2. Add to onCreate function the following code:
    import android.content.Context
    import android.net.wifi.WifiManager
    val wifi = getSystemService(Context.WIFI_SERVICE).asInstanceOf[WifiManager]
    wifi.disconnect()
  3. Go ahead and run the project
  4. Open the manifest and confirm that the permissions were added.

Internally, this mostly achieved by looking at the application's callgraph and comparing to the results of PScout, which contains a mapping between permissions and specific Android's functions.

It should be noted that this technique might miss a permission or add some unnecessarily. Before deploying to production the application, the permissions list should be revisited.

Scaffolding

Scaffold is a command that takes a model, looks at its attributes, and creates the views and controllers needed to implement the List and CRUD (Create, Read, Update, Delete) operations in Android. The concept is similiar in several known web applications frameworks, such as Rails and Django.

To execute scaffold task in existing model use the command:

scaffold <Model Name>

Continuing with our previous example, lets scaffold the model Post:

  1. Open the SBT console in the project directory, and type:

    scaffold Post

  2. At this point, we can look at the resources created in the layout folder, and in the ui folder.
  3. At this point, running the project would still open the MainActivity. To change this, open themanifest and replace MainActivity with PostMainActivity.
  4. Now run the project, and experiment.

Here's a quick preview of the generated model's view:

What if you change the model after the scaffold was performed? In this case, you can either edit the source code manually as you would when developing an Android application without assistance, or delete the source code in the ui folder related to the model and scaffold it again.

Scaffolding should be a seen as a starting point in an application development and not the final result. The code generated is very human-readable and modular. Sometimes for functional rapid-prototyping, scaffolding a model might just be enough.

Wrap up

Thanks for following this tutorial. The basics of using this tool were covered here, for more information, go to the project website.

Feel free to open a issue there for suggestions and bug reporting.

comments powered by Disqus