Overcoming Android's Problems with JDK 7, Part 2
Be sure to start with Part 1 of this series.
Google doesn't include JDK 7 in Android's system requirements, but you can still use this JDK to develop Android apps. Before doing so, you need to be aware of three problems that are bound to plague you during development, which is the focus of this two-part series. Last time, I discussed JAR library creation and release mode APK signing problems. This article completes this series by introducing you to the third problem of how to support Java 7-specific language features and showing you how to overcome it.
Supporting Java 7-Specific Language Features
Java 7 introduced several new language features with switch-on-string and try-with-resources being notable. You probably want to use these features in your app's source code, but don't feel hopeful, especially after learning that you must specify -source 1.5 and -target 1.5 (or -source 1.6 and -target 1.6) when compiling library source code. However, it's not difficult to make Android support these features.
Supporting Switch-on-String
Java 7's new language features can be categorized into those that depend on new or enhanced APIs (the try-with-resources statement fits into this category), and those that don't. The switch-on-string feature fits into the latter category, making it easier to support. Consider Listing 1, which presents an expanded Utils class that uses switch-on-string.
Listing 1The 3 in month3 is a reminder that the month name must be at least three characters long.
package ca.tutortutor.utils; public class Utils { public static int daysInMonth(String month3) { if (month3.length() < 3) throw new IllegalArgumentException("< 3"); switch (month3.toUpperCase().substring(0, 3)) { case "JAN": return 31; case "FEB": return 28; case "MAR": return 31; case "APR": return 30; case "MAY": return 31; case "JUN": return 30; case "JUL": case "AUG": return 31; case "SEP": return 30; case "OCT": return 31; case "NOV": return 30; case "DEC": return 31; default : return 0; } } public static int rnd(int limit) { // Return random integer between 0 and limit (exclusive). return (int) (Math.random()*limit); } }
Listing 1's int daysInMonth(String month3) method uses switch-on-string to return the number of days in the month whose name is passed to the switch statement. For February, leap years are not recognized, and 28 is always returned. If the month name is invalid, and a java.lang.IllegalArgumentException or java.lang.NullPointerException instance isn't thrown, 0 is returned.
Listing 2 presents an updated UseUtils activity class that demonstrates daysInMonth(String).
Listing 2Toasting startup by presenting a randomly generated month name and its number of days.
package ca.tutortutor.useutils; import android.app.Activity; import android.os.Bundle; import android.widget.Toast; import ca.tutortutor.utils.Utils; public class UseUtils extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); String[] months = { "January", "February (non-leap year)", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; int m = Utils.rnd(12); Toast.makeText(this, months[m]+" has "+Utils.daysInMonth(months[m])+ " days.", Toast.LENGTH_LONG).show(); } }
Create the library by completing the following steps:
- Create a ca\tutortutor\utils directory hierarchy under the current directory (if it doesn't exist).
- Copy a Utils.java source file containing Listing 1 into utils.
- From the current directory, execute javac ca/tutortutor/utils/Utils.java to compile this file.
- From the current directory, execute jar cf utils.jar ca/tutortutor/utils/*.class to create utils.jar.
Copy utils.jar to the UseUtils\libs directory, and replace the src\ca\tutortutor\useutils\UseUtils.java file with Listing 2.
Before you can build this project, you need to modify the build.xml file that's stored in the tools\ant subdirectory hierarchy of your Android SDK's home directory. For example, this directory is C:\android\tools\ant on my platform. Before making this change, back up build.xml so that you can revert to the original file if necessary.
Locate the following <macrodef> element in build.xml:
<macrodef name="dex-helper"> <element name="external-libs" optional="yes" /> <attribute name="nolocals" default="false" /> <sequential> <!-- sets the primary input for dex. If a pre-dex task sets it to something else this has no effect --> <property name="out.dex.input.absolute.dir" value="${out.classes.absolute.dir}" /> <!-- set the secondary dx input: the project (and library) jar files If a pre-dex task sets it to something else this has no effect --> <if> <condition> <isreference refid="out.dex.jar.input.ref" /> </condition> <else> <path id="out.dex.jar.input.ref"> <path refid="project.all.jars.path" /> </path> </else> </if> <dex executable="${dx}" output="${intermediate.dex.file}" nolocals="@{nolocals}" verbose="${verbose}"> <path path="${out.dex.input.absolute.dir}"/> <path refid="out.dex.jar.input.ref" /> <external-libs /> </dex> </sequential> </macrodef>
This element encapsulates a <dex> element that runs the dx tool. dx combines the equivalent of Java classes into a classes.dex file, but ignores classes that target Java 7, which is why you previously used the -source and -target options when creating a JAR library. Those options don't work in this context because Java 7's switch-on-string feature is used. Instead, you must specify dx's --no-strict option.
Unfortunately, there's no way to specify --no-strict in the context of the aforementioned <dex> element. You can prove this to yourself by unzipping the anttasks.jar file (in the tools\lib subdirectory of the SDK's home directory), locating the DexExecTask.class classfile, and executing javap DexExecTask. You should observe the following output:
Compiled from "DexExecTask.java" public class com.android.ant.DexExecTask extends com.android.ant.SingleDependencyTask { public com.android.ant.DexExecTask(); public void setExecutable(org.apache.tools.ant.types.Path); public void setVerbose(boolean); public void setOutput(org.apache.tools.ant.types.Path); public void setNoLocals(boolean); public java.lang.Object createPath(); public java.lang.Object createFileSet(); public void execute() throws org.apache.tools.ant.BuildException; protected java.lang.String getExecTaskName(); }
Nothing in this class refers to --no-strict.
To solve this problem, prepend an underscore to the current <macrodef> element's dex-helper name and insert the following <macrodef>:
<macrodef name="dex-helper"> <element name="external-libs" optional="yes" /> <element name="extra-parameters" optional="yes" /> <sequential> <!-- sets the primary input for dex. If a pre-dex task sets it to something else this has no effect --> <property name="out.dex.input.absolute.dir" value="${out.classes.absolute.dir}" /> <!-- set the secondary dx input: the project (and library) jar files If a pre-dex task sets it to something else this has no effect --> <if> <condition> <isreference refid="out.dex.jar.input.ref" /> </condition> <else> <path id="out.dex.jar.input.ref"> <path refid="project.all.jars.path" /> </path> </else> </if> <apply executable="${dx}" failonerror="true" parallel="true"> <arg value="--dex" /> <arg value="--no-locals" /> <arg value="--verbose" /> <arg value="--output=${intermediate.dex.file}" /> <arg value="--no-strict" /> <extra-parameters /> <arg path="${out.dex.input.absolute.dir}" /> <path refid="out.dex.jar.input.ref" /> <external-libs /> </apply> </sequential> </macrodef>
This <macrodef> element will be executed in place of the original <macrodef> element because that element's name has been changed slightly. It uses Ant's <apply> element to execute dx as a system command, and gives greater flexibility as to the options that can be passed to dx via nested <arg> elements.
Build the APK via ant debug. Then, install the APK on the device and run the app. Figure 1 shows you what you might observe.
Figure 1 You are greeted with a randomly generated month name and the number of days in that month.
Supporting Try-with-Resources
The try-with-resources statement is harder to support because it depends on two external APIs: a new java.lang.AutoCloseable interface that is the java.io.Closeable interface's parent, but with slightly different exception-oriented semantics; and an enhanced java.lang.Throwable class that supports suppressed exceptions. These dependencies raise three problems:
- Distributing AutoCloseable and Throwable classes: You cannot distribute the AutoCloseable and Throwable classes that are included in Oracle's JDK 7 reference implementation because of license restrictions.
- Retrofitting existing classes: Classes designed for use with try-with-resources must implement AutoCloseable or its Closeable subinterface. How do you retrofit an existing class such as java.io.FileInputStream to meet this requirement?
- Overriding the existing Throwable class: Java 5's version of Throwable doesn't support suppressed exceptions. You must make sure that the overriding version of this class (with this support) is accessed when an app is built.
The first problem can be solved by obtaining the OpenJDK version of these classes, as follows:
- Point your browser to http://download.java.net/openjdk/jdk7/.
- Download openjdk-7-fcs-src-b147-27_jun_2011.zip. This ZIP file contains the OpenJDK equivalent of JDK 7. Most of its code is released under the GNU General Public License Version 2 (GPLv2).
- Unarchive this ZIP file and extract its openjdk/jdk/src/share/classes/java/lang/AutoCloseable.java and openjdk/jdk/src/share/classes/java/lang/Throwable.java source files.
Complete the following steps to compile these source files and store their classfiles in a core.jar library:
- Create a java\lang directory hierarchy under the current directory.
- Copy these source files into lang.
- From the current directory, execute javac java/lang/*.java to compile both files.
- From the current directory, execute jar cf core.jar java/lang/*.class to create core.jar.
Copy core.jar to the UseUtils\libs directory.
The second problem can be solved by using composition. Check out Listings 3 and 4.
Listing 3_FileInputStream encapsulates its FileInputStream counterpart.
package ca.tutortutor.autocloseables; import java.io.FileInputStream; import java.io.IOException; public class _FileInputStream implements AutoCloseable { private FileInputStream fis; public _FileInputStream(String filename) throws IOException { fis = new FileInputStream(filename); } public int read() throws IOException { return fis.read(); } @Override public void close() throws IOException { System.out.println("instream closed"); fis.close(); } }
Listing 4_FileOutputStream encapsulates its FileOutputStream counterpart.
package ca.tutortutor.autocloseables; import java.io.FileOutputStream; import java.io.IOException; public class _FileOutputStream implements AutoCloseable { private FileOutputStream fos; public _FileOutputStream(String filename) throws IOException { fos = new FileOutputStream(filename); } public void write(int _byte) throws IOException { fos.write(_byte); } @Override public void close() throws IOException { System.out.println("outstream closed"); fos.close(); } }
Listing 3's and 4's _FileInputStream and _FileOutputStream classes implement AutoCloseable in terms of its close() method, changing the method's exception type to be compliant with the actual stream classes. A suitable constructor is declared to instantiate the stream class, and an I/O method is provided to delegate to the encapsulated instance's I/O method.
Complete the following steps to compile these source files and store their classfiles in an autocloseables.jar library:
- Create a ca\tutortutor\autocloseables directory hierarchy under the current directory.
- Copy the _FileInputStream.java and _FileOutputStream.java source files containing Listings 3 and 4 (respectively) into autocloseables.
- From the current directory, execute javac ca/tutortutor/autocloseables/*.java to compile both files.
- From the current directory, execute jar cf autocloseables.jar ca/tutortutor/autocloseables/*.class to create autocloseables.jar.
Copy autocloseables.jar to the UseUtils\libs directory.
Before solving the third problem, consider Listing 5, which presents an expanded Utils class that uses try-with-resources.
Listing 5You can catenate zero or more files to each other.
package ca.tutortutor.utils; import ca.tutortutor.autocloseables._FileInputStream; import ca.tutortutor.autocloseables._FileOutputStream; import java.io.IOException; public class Utils { public static boolean cat(String outfilename, String... infilenames) { try (_FileOutputStream fos = new _FileOutputStream(outfilename)) { for (String infilename: infilenames) try (_FileInputStream fis = new _FileInputStream(infilename)) { int _byte; while ((_byte = fis.read()) != -1) fos.write(_byte); } catch (IOException ioe) { return false; } return true; } catch (IOException ioe) { return false; } } public static int daysInMonth(String month3) { if (month3.length() < 3) throw new IllegalArgumentException("< 3"); switch (month3.toUpperCase().substring(0, 3)) { case "JAN": return 31; case "FEB": return 28; case "MAR": return 31; case "APR": return 30; case "MAY": return 31; case "JUN": return 30; case "JUL": case "AUG": return 31; case "SEP": return 30; case "OCT": return 31; case "NOV": return 30; case "DEC": return 31; default : return 0; } } public static int rnd(int limit) { // Return random integer between 0 and limit (exclusive). return (int) (Math.random()*limit); } }
Listing 5's boolean cat(String outfilename, String... infilenames) method uses try-with-resources to ensure that the _FileInputStream and _FileOutputStream instances are closed regardless of a thrown exception. This method returns false when an exception is thrown (the output file may contain content), or true when the method finishes normally (the output file contains all content).
Listing 6 presents an updated UseUtils class that demonstrates cat(String, String...).
Listing 6Toasting startup by presenting catenated data items.
package ca.tutortutor.useutils; import android.app.Activity; import android.os.Bundle; import android.widget.Toast; import ca.tutortutor.autocloseables._FileInputStream; import ca.tutortutor.autocloseables._FileOutputStream; import ca.tutortutor.utils.Utils; import java.io.IOException; public class UseUtils extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try (_FileOutputStream fos = new _FileOutputStream("/sdcard/data.dat")) { fos.write(10); fos.write(20); } catch (IOException ioe) { Toast.makeText(this, "I/O error: "+ioe.getMessage(), Toast.LENGTH_LONG).show(); return; } boolean isOk = Utils.cat("/sdcard/merged.dat", "/sdcard/data.dat", "/sdcard/data.dat"); if (!isOk) { Toast.makeText(this, "unable to merge two instances of data.dat", Toast.LENGTH_LONG).show(); return; } try (_FileInputStream fis = new _FileInputStream("/sdcard/merged.dat")) { int data1 = fis.read(); int data2 = fis.read(); int data3 = fis.read(); int data4 = fis.read(); Toast.makeText(this, "Read data: "+data1+" "+data2+" "+data3+" " +data4, Toast.LENGTH_LONG).show(); } catch (IOException ioe) { Toast.makeText(this, "I/O error: "+ioe.getMessage(), Toast.LENGTH_LONG).show(); return; } } }
Create the library by completing the following steps:
- Create a ca\tutortutor\utils directory hierarchy under the current directory (if it doesn't exist).
- Copy a Utils.java source file containing Listing 5 into utils.
- Copy the previously created autocloseables.jar file into the current directory.
- From the current directory, execute javac -cp autocloseables.jar ca/tutortutor/utils/Utils.java to compile this file.
- From the current directory, execute jar cf utils.jar ca/tutortutor/utils/*.class to create utils.jar.
Copy utils.jar to the UseUtils\libs directory, and replace the src\ca\tutortutor\useutils\UseUtils.java file with Listing 6.
Any attempt to build this project (ant debug) at this point results in the following error message:
-compile: [javac] Compiling 3 source files to C:\prj\dev\UseUtils\bin\classes [javac] C:\prj\dev\UseUtils\src\ca\tutortutor\useutils\UseUtils.java:24: error: try-with-resources is not supported in -source 1.5 [javac] try (_FileOutputStream fos = new _FileOutputStream("/sdcard/data.dat")) [javac] ^ [javac] (use -source 7 or higher to enable try-with-resources) [javac] 1 error
This error message is generated because Listing 6 uses try-with-resources. In contrast, Listing 2 doesn't use any language feature or API not supported by Android. The build.xml file's <javac> element accesses the following properties, which prevent javac from compiling any source code newer than Java 1.5:
<property name="java.target" value="1.5" /> <property name="java.source" value="1.5" />
Change each 1.5 occurrence to 1.7 and rebuild. This time, you'll discover the following error message:
-compile: [javac] Compiling 3 source files to C:\prj\dev\UseUtils\bin\classes [javac] C:\prj\dev\UseUtils\src\ca\tutortutor\useutils\UseUtils.java:24: error: cannot find symbol [javac] try (_FileOutputStream fos = new _FileOutputStream("/sdcard/data.dat")) [javac] ^ [javac] symbol: method addSuppressed(Throwable) [javac] location: class Throwable [javac] Fatal Error: Unable to find method addSuppressed
This error message results from the default version of the Throwable class (located in the SDK platform's android.jar file) and not the version of this class located in the autocloseables.jar file being accessed. To fix this final problem, you need to make two more adjustments to build.xml.
The first adjustment is to add the following <path> element above the <javac> element:
<path id="project.bootpath"> <pathelement location="libs/core.jar" /> <path refid="project.target.class.path" /> </path>
and then change the value of <javac>'s bootclasspathref attribute from project.target.class.path to project.bootpath.
The second adjustment is to insert <arg value="--core-library" /> into the <apply> element that's part of the revised <macrodef> element whose name attribute is assigned dex-helper. The --core-library option tells dx to not generate the following message and fail a build when encountering a core API:
[apply] trouble processing "java/lang/AutoCloseable.class": [apply] [apply] Ill-advised or mistaken usage of a core class (java.* or javax.*) [apply] when not building a core library. [apply] [apply] This is often due to inadvertently including a core library file [apply] in your application's project, when using an IDE (such as [apply] Eclipse). If you are sure you're not intentionally defining a [apply] core class, then this is the most likely explanation of what's [apply] going on. [apply] [apply] However, you might actually be trying to define a class in a core [apply] namespace, the source of which you may have taken, for example, [apply] from a non-Android virtual machine project. This will most [apply] assuredly not work. At a minimum, it jeopardizes the [apply] compatibility of your app with future versions of the platform. [apply] It is also often of questionable legality. [apply] [apply] If you really intend to build a core library -- which is only [apply] appropriate as part of creating a full virtual machine [apply] distribution, as opposed to compiling an application -- then use [apply] the "--core-library" option to suppress this error message. [apply] [apply] If you go ahead and use "--core-library" but are in fact [apply] building an application, then be forewarned that your application [apply] will still fail to build or run, at some point. Please be [apply] prepared for angry customers who find, for example, that your [apply] application ceases to function once they upgrade their operating [apply] system. You will be to blame for this problem. [apply] [apply] If you are legitimately using some code that happens to be in a [apply] core package, then the easiest safe alternative you have is to [apply] repackage that code. That is, move the classes in question into [apply] your own package namespace. This means that they will never be in [apply] conflict with core system classes. JarJar is a tool that may help [apply] you in this endeavor. If you find that you cannot do this, then [apply] that is an indication that the path you are on will ultimately [apply] lead to pain, suffering, grief, and lamentation. [apply] [apply] 1 error; aborting
Build the APK via ant debug. If successful, install the APK on the device, and run the app. Figure 2 shows you what you should observe.
Figure 2 You are greeted with two identical pairs of data items.
If you're wondering whether or not the try-with-resources statement is working, check out Figure 3.
Figure 3 Android's log output reveals outstream closed and instream closed messages.
Figure 3 reveals a sequence of outstream closed and instream closed messages. The first outstream closed message is associated with the _FileOutputStream object that's created in Listing 6. The two instream closed messages that follow are associated with the _FileInputStream objects that are created inside the cat(String, String...) method.
Continuing, the outstream closed message that follows is associated with the _FileOutputStream object that is also created inside cat(String, String...). Finally, the last instream closed message is associated with the _FileInputStream object that's created after the _FileOutputStream object in Listing 6.