Open Talk: A Whirlwind Tour of Gradle for Android with Mark Murphy, June 17

A Whirlwind Tour of Gradle for Android

The Android tools team has been hard at work developing an Android plugin for the Gradle build system, with an eye towards Gradle for Android replacing the venerable Ant for automated builds. Gradle for Android is also used by Android Studio, the new Android IDE, for its builds. In this presentation, we will explore what Gradle for Android is, what problems it solves, how to get started playing with Gradle for Android, and how to take advantage of some of its basic features. Attendees will leave with a better understanding of why Gradle for Android is important for all Android developers in 2014 and beyond.

About the presenters

Mark Murphy is the founder of CommonsWare and the author of The Busy Coder’s Guide to Android Development. He is active in supporting the Android developer community, from answering questions on StackOverflow to publishing sample code and reusable components as open source.

A three-time entrepreneur, his experience ranges from consulting on open source and collaborative development for the Fortune 500 to application development on just about anything smaller than a mainframe. He has been a software developer for nearly three decades, from the TRS-80 to the latest crop of mobile devices. A polished speaker, Mr. Murphy has delivered conference presentations and training sessions on a wide array of topics internationally.

RSVP Here.

Android Debug Bridge (ADB) command scripting

The Android Debug Bridge (ADB) is a useful tool for testing and debugging, though it can be cumbersome to use given its broad set of options. For example, testing an app might require frequent authentication, and just sending the username with adb looks like this:

Command aliases can simplify this. In bash, these can be added to the startup script, such as .bashrc:

Now the username can be passed by simply typing:

Windows users can do something similar using Doskey.

The password could be sent using a similar alias:

Since other text might be sent, and those aliases can be chained together, you could setup the following:

Next, add in some keyevents for navigating between the fields:

Now, the whole login flow can be performed using a single command, such as applogin:

This can be handy for simple and frequent app interaction while testing. I use scripts such as these to navigate through initial activities during a fresh app launch to get me to the point where I need to test or debug quickly.

A similar approach to all of this is to use monkeyrunner, or continuing down that route, testing using something like calabash, but for something quick, I find that this fits the bill.

Here is a larger set of adb option aliases, comprising my basic day to day needs:

 

Interesting? 

Do you find this sort of work interesting? Do you love quaint Bucks County Pennsylvania? Are you an amazing Android Developer? Then we would love to hear from you!

Android Image Credit: Copyright Pinada, CC BY-ND 3.0

Best Practices for Consuming APIs On Android

First Some History

Up until fairly recently integrating APIs into your Android application had been the wild west. Each application had their own networking and caching implementations that were generally pretty brittle and didn’t handle non optimal networking conditions terribly well.

Thanks largely to Square Inc, the innovative company bringing credit card processing for businesses to mobile phones, there is now a wealth of high quality open source libraries available that support API integration in your Android applications.

What will we learn how to do?

In this post, we will learn how to use a Retrofit, OkHttp and GSON stack in order to be able to simply and robustly integrate a REST API into your application. Using this stack we will download and parse some data from Twitch.tv.  Following the steps outlined, you will be able to integrate most REST APIs into your application in just a few minutes, without writing any boilerplate code.

Lets Learn About the Stack

Retrofit

Retrofit makes it incredibly easy to download JSON or XML data from a web API and parse it into a Plain Old Java Object (POJO). For example to download a users repo information from Github all the code you need to write is:

Additionally you would need to create the Repo POJO so that the parser knows what type of data you are expecting from that endpoint.  This code can be auto-generated, more on this later.

Its just as easy to provide query parameters or do POST or HEAD requests. For instructions for how to connect with different types of APIs just see the documentation.

One of the nice features of Retrofit is the ability to add additional logic to all requests and responses. You could for instance add additional data to all request HTTP headers or intercept any unauthorized response error codes and redirect the user to your login screen.

OkHttp

OkHttp is an HTTP client for Android applications. It is efficient by default and includes support for SPDY, connection pooling, GZIP, and a HTTP response cache.

In addition OkHttp handles common networking issues automatically and silently such as retries and SSL handshake issues. Retrofit will use OkHttp automatically as its networking layer if it is present in your application.

GSON

GSON is a Java library that is used to parse JSON data into a POJO. It can also be used to convert a POJO into JSON, which in Android can be helpful as a way to store generic objects into shared preferences.

To use GSON you essentially just need to create a representative POJO of the data you wish to parse and run GSON on the data to parse it into an instance of the POJO. Its dead simple and makes parsing a breeze. To learn how to create your POJOs compatible with GSON see the documentation. Retrofit uses GSON in order to do its JSON parsing.

Lets do Some Coding!

Add the libraries to your project

  1. Download the jar files for Retrofit, OkHttp, and GSON.
  2. Drag each of the jar files into your libs folder in your project
  3. If using Android Studio Sync the project with gradle

Find or write an API

You probably already have an API in mind but if you are looking for a directory of APIs I recommend ProgrammableWeb. For the purposes of this tutorial we are going to be parsing a list of streams available from Twitch.tv. To see the request format see their API documentation. The basic API request to get the list of steams from Twitch.tv in JSON format is: http://api.justin.tv/api/stream/list.json

Capture Some Sample Output

In order to proceed we need some sample data that is returned from the API. In this case since it is a GET request we can just run the request in a web browser, and copy out the response such as:

[{“broadcast_part”: 4, “featured”: true, “channel_subscription”: true, “audio_codec”: “uncompressed”, “id”: “6640712464”, “category”: “gaming”, “title”: “Fnatic xPeke, Normals(ranked down) on smurf”, “geo”: “DE”, “video_height”: 1080, “site_count”: 8014, “embed_enabled”: true, “channel”: {“subcategory”: null, “producer”: true, “image_url_huge”: “http://static-cdn.jtvnw.net/jtv_user_pictures/xpeke-profile_image-a182a5fe5a8f239b-600×600.jpeg”, “timezone”: “Europe/Madrid”, “screen_cap_url_huge”: “http://static

Generate the POJOs for your data

Now for the fun part, using the sample data we just captured we are going to auto generate the POJOs that represent that data. Use jsonschema2pojo and be sure to enter in your desired package name, class name, JSON as the type, and use primitive types. For this example the generator got confused because the root of the JSON is an array and not an object; so I only pasted in the first element of the array. Some fiddling may be necessary.

POJO-Generator

Integrate the Generated POJOs Into Your Code

With the POJOs generated now we can just paste those generated classes into our project. In my sample project they are in the models package.

Use Retrofit to Download/Parse the API

Create a Rest Adapter

Creating the adapter is as simple as setting the endpoint:

Define the APIs interfaces

Define the interface for each endpoint you are going to connect with. In this case we are connecting to the steams endpoint with the limit and offset parameters which are used for paging the data. These are specified in the Justin.Tv API documentation.

You will notice we are expecting back a response from the endpoint that is a List of JustinTvStreamData objects, which is the POJO we auto-generated earlier. For more information on how to define this interface see the Retrofit documentation.

Create the Twitch.Tv Service

Now that we have the endpoint established and the interface defined we need to make the Twitch.Tv service that allows making requests.

Hit the API

Making the API request is equally simple.  We just need to use the service we just created.

What is interesting here in the fact that Retrofit will download and parse the API data on a background thread, and then deliver the results back to the UI thread via the success or failure method. Retrofit also supports just downloading on whatever thread it is called on (not shown here).

Do Something Interesting With the Data

Now that the data is in a POJO do something interesting with it!
For this demo project I display the Twitch.Tv channel image and description and used the Picasso Library to download and cache the images.

TwitchClient

References

Open Source Sample Project

Interesting? 

Do you find this sort of work interesting? Do you love quaint Bucks County Pennsylvania? Are you an amazing Android Developer? Then we would love to hear from you!

Android Tricks and Tips: Storing a POJO Into Shared Preferences

Often you will yourself with the need for storing some simple persistent data in your Android application. Maybe you are tracking the last time you showed a user an upsell dialog? Perhaps you want to know if this is the first time onto a screen so you can show some new user experience flow.

Shared Preferences to the rescue! Sweet! All I need to do is store my Plain Old Java Object into a shared preference key and we are all set. So you open up the interface document for the Shared Preference editor class to see which method to call.

SharedPreferences Editor Interface

Wait a minute? I only see interfaces for basic Java types? No support for Parcelable or Serializable? Looks like there is no way to just store a POJO into Shared Preferences. Or is there…

GSON to the rescue! GSON is a beautiful Java utility library that allows converting to and from JSON and POJOs.

Saving to the Shared Preference

  1. Integrate the GSON library into your project. (Just download the jar and drag it into your libs folder)
  2. Create the POJO
  3. Serialize the POJO into a JSON String using GSON
  4. Save the serialized POJO into your shared preference

Restoring from the Shared Preference

  1. Read the shared preference value into a string
  2. Using GSON convert the serialized string back into your POJO

Time for Some Code!

First lets take a look at our class that we want to save and restore from a Shared Preference. What is important to notice is we have encapsulated the serialization and deserialization into the class.

Now lets take a look at the code to store and retrieve the POJO from the Shared Preference.

Interesting?

Do you find this sort of work interesting? Do you love quaint Bucks County Pennsylvania? Are you an amazing Android Developer? Then we would love to hear from you!

A Tale of Migrating From Eclipse to Android Studio

I have recently done the unthinkable and taken the plunge into full time use of Android Studio over Eclipse for my Android development. This was not willingly mind you, but as a necessity since the project I was to work on was using Android Studio along with its Gradle build system.

After several months of using Android Studio as my full time IDE I have just one thing to say:

I will never go back to Eclipse

Through the years Eclipse has treated me fairly well and is a robust IDE that I have become quite expert at, but anyone that has used it for any length of time for Android development is aware of some of its shortcomings:

  • It has a tendency to get slower and crash more often with each successive release
  • In order for it to run for more than a few hours you need to edit the config files to give it massive amounts of RAM
  • It tends to run out of memory and crash when you are trying to export an APK
  • It requires a massive amount of CPU power to use it without getting a please wait beach ball every few seconds. I built a quad core 4.5 GHz machine just to make it usable as my daily driver.
  • Theme support is fairly mediocre, there are plugins to add support however none of them theme anything but the code window.
  • Creating UI for Android is extremely clunky
  • Anytime you touch a file outside of Eclipse you need to tell it to refresh itself. Anyone that works on multiple code branches every day will quickly realize it is very easy to forget to do this.
  • There is a mysterious need to constantly “clean” the project. Changed a file not using the editor? Better refresh then clean. Modified just an XML file but not any code files? Better clean or that XML modification probably won’t make it in the build, or worse yet the string values will all offset by one from what they should be.

Welcome our new robot overlords

Android Studio is a welcome change that addresses many of this laundry list of issues in Eclipse and installation is as simple as downloading and dragging it to your applications folder. The first thing you will notice is you can now theme the entire program and it looks beautiful!

Android Studio

Some key improvements

  • Full theming takes away much of the eye strain I was getting with Eclipse
  • Very stable and does not leak memory forcing constant reboots
  • The UI creation tools are vastly improved
  • No refreshing! The editor automatically updates itself whenever files are changed outside of the editor. No need to refresh every time I change branches.
  • There is no need to constantly clean my projects!
  • Command clicking on Android related items actually works. For instance command click on an android id and it opens the XML file it is defined in.

Stability

Android Studio has multiple builds in the wild including canary, dev, and beta. I do not recommend running the canary build as it tends to be quite buggy. I recommend running the dev build. After running the dev builds for over four months now I can say that it is a much more stabile development environment than Eclipse. Performance is good and I have never had to close and reopen the program because it was slowing leaking more and more memory and getting slower and slower.

For the Eclipse Convert

An incredible feature is the ability to set your hotkeys to the same that are used in Eclipse. For myself, the main reason I had held out was an intense fear of having to relearn all of the hotkeys I use daily.

UI Creation is Better

Creating UI in Eclipse is painful; not only do you have to constantly toggle between the XML tab and the rendering tab to check your work, but you have to do it twice every time because of a bug where the first time it doesn’t always render correctly. Android Studio UI In Android Studio you can actually see the UI rendered as you type the XML. Not only that, but you can click on the fields in the rendering and jump right to the XML. Additionally there is support for design time attributes which allows you to add things like text in each of your TextViews to aid in designing your XML. No longer do you have to design everything with canned data so its not invisible only to have to delete it before you actually commit your code.

Gradle Gradle Gradle

The biggest hurdle to overcome with your transition to Android Studio is that is uses a different build environment in Gradle. While there is absolutely a learning curve here most of the common questions have already been answered on StackOverflow. In addition Eclipse has a new option to aid in migrating from Eclipse to Gradle and migration is generally pretty straightforward.

The first time you try to add a library project or jar file you will need to relearn the process, but once you have it really is pretty trivial. One drawback is many open source libraries do not have Gradle support yet so you will need to use Eclipse to export and add Gradle support. While you are at it why not upload them back to the source repo? Its a great way to move things forward and get some easy Github cred.

Gradle has some real advantages over what you are used to in Eclipse:

  • The build process is scripted, meaning you can add useful dynamic features to it
  • Adding a GUI toggle for build variants is pretty easy. Want an internal build and a store build? An Amazon and Google build?
  • You can export APKs with the version number in the filename
  • You can run a script when your APK is created; for instance to automatically upload the APK to TestFlight for internal testing

Interesting? 

Do you find this sort of work interesting? Do you love quaint Bucks County Pennsylvania? Are you an amazing Android Developer? Then we would love to hear from you!