Unity3D for Android: Using a Native Java Plugin to Grab the Android Device ID

The java code returns an MEID (Android Device ID) on CDMA phones (Verizon, Sprint), an IMEI on GSM phones (AT&T, T Mobile) and an Android ID on WIFI-only devices (no cellular network).

This code is based on Android Java Plugin for Unity example project in the Unity manual.

Why bother with a plugin?

I tried using Unity 3.5’s built-in SystemInfo.deviceUniqueIdentifier getter for obtaining a unique device ID but it didn’t meet our ad network’s requirements.

The set up in Unity 3.5

  • Drag the AndroidJava.jar file inside /Assets/Plugins/Android/. /Assets/Plugins/Android/bin/ worked too. This .jar file is created via Eclipse or command line javac based on the Java source code
  • Drag the example libjni.so file inside /Assets/Plugins/Android/. Make sure it’s inside /Plugins/Android or you’ll get a “DllNotFoundException: jni” error when you test on device with adb.
  • Drag JNI.cs into /Assets/Plugins/
  • Drag JavaVM.cs into /Assets/Plugins/
  • Make sure your project has an AndroidManifest.xml file inside /Assets/Plugins/Android/ with android.permission.READ_PHONE_STATE permission set. android.permission.READ_PHONE_STATE is needed to access an Android phone/tablet’s Android ID, IMEI or MEID. If you’re making HTTP calls you’ll also need additional permissions, etc.

Code that worked:

...
	private static IntPtr	JavaClass; 
	private static int		GetDeviceId;
...

	///if you're calling the plugin from a static method, you still have to make sure an instance of this script is attached to 
	///an empty GameObject in Hierarchy so Start() method runs & the below code initializes:	
	void Start() {
		
		#if UNITY_ANDROID 		
		
			// attach our thread to the java vm; obviously the main thread is already attached but this is good practice..
			JavaVM.AttachCurrentThread();
			
			// first we try to find our main activity..
			IntPtr cls_Activity		= JNI.FindClass("com/unity3d/player/UnityPlayer");
			int fid_Activity		= JNI.GetStaticFieldID(cls_Activity, "currentActivity", "Landroid/app/Activity;");
			IntPtr obj_Activity		= JNI.GetStaticObjectField(cls_Activity, fid_Activity);
			Debug.Log("obj_Activity = " + obj_Activity);		
			
			// create a JavaClass object...
               //"com/yourCompany/yourProjectName" should be your Bundle ID in Unity's Player Settings & should be the package name in your Java class
			IntPtr cls_JavaClass	= JNI.FindClass("com/yourCompany/yourProjectName/JavaClass"); 	
			int mid_JavaClass		= JNI.GetMethodID(cls_JavaClass, "<init>", "(Landroid/app/Activity;)V");
			IntPtr obj_JavaClass	= JNI.NewObject(cls_JavaClass, mid_JavaClass, obj_Activity);
			Debug.Log("java Helper object = " + obj_JavaClass);		
			
			// create a global reference to the JavaClass object and fetch method id(s)..
			JavaClass					= JNI.NewGlobalRef(obj_JavaClass);
			GetDeviceId					= JNI.GetMethodID(cls_JavaClass, "GetDeviceId", "()Ljava/lang/String;");
			Debug.Log("JavaClass global ref = " + JavaClass);
			Debug.Log("JavaClass GetDeviceId method id = " + GetDeviceId);						
		
		#endif			
	}	
...

	/// <summary>
	/// Gets the unique device for Android devices (IMEI, MEID or Android ID).
	/// </summary>
	/// <returns>
	/// Returns the id as a string.
	/// </returns>
	private string GetTheDeviceID()
	{		
		//didn't work... supposed to return IMEI but didn't 
		//return SystemInfo.deviceUniqueIdentifier;
		
		String dID = "";
		
		#if UNITY_ANDROID 
	
			// again, make sure the thread is attached..
			JavaVM.AttachCurrentThread();
						
			// get the Java String object from the Helper java object
			IntPtr str_cacheDir 	= JNI.CallObjectMethod(JavaClass, GetDeviceId);
			Debug.Log("str_cacheDir = " + str_cacheDir);		
			
			// convert the Java String into a Mono string
			IntPtr stringPtr = JNI.GetStringUTFChars(str_cacheDir, 0);
			Debug.Log("stringPtr = " +stringPtr);
			dID = Marshal.PtrToStringAnsi(stringPtr);
			JNI.ReleaseStringUTFChars(str_cacheDir, stringPtr); 		
					
		#endif

		Debug.Log(" Device ID value is = " + dID);
		
		return devID;		
	}		

/// call GetTheDeviceID() when you need to use it
...

The Java Code

The below code is based on requirements by ad networks that need to use a specific device ID for metrics like conversion tracking. It’s the main source file for generating the AndroidJava.jar you need to import into Unity’s Plugins folder.

The Device ID & hashing methods implementations come directly from Millennial Media‘s public wiki.

package com.yourCompany.yourProjectName;

import android.app.Activity;
import android.content.Context;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.util.Log;
import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class JavaClass
{
	private Activity mActivity;
	
	public JavaClass(Activity currentActivity)
	{
		Log.i("JavaClass", "Constructor called with currentActivity = " + currentActivity);
		mActivity = currentActivity;
	}
	
	public String GetDeviceId()
	{		
		// Get the device ID
        String auid = android.provider.Settings.Secure.ANDROID_ID + "android_id";
        
        Context context = mActivity.getApplicationContext();
        
        TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        if(tm != null)
        {
             try{
             auid = tm.getDeviceId();
             }
             catch (SecurityException e){
                  e.printStackTrace();
             }
             tm = null;
        }
        if(((auid == null) || (auid.length() == 0)) && (context != null))
             auid = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
        if((auid == null) || (auid.length() == 0))
             auid = null;
        
        return auid;	
	}
	
	public String GetHashedDeviceIdSHA1()
	{
		String deviceId = GetDeviceId();
		
		String hashedDeviceId = hashInputSHA1(deviceId);
		
		return hashedDeviceId;
	}
	
	public String GetHashedDeviceIdMD5()
	{
		String deviceId = GetDeviceId();
		
		String hashedDeviceId = hashInputMD5(deviceId);
		
		return hashedDeviceId;
	}

	
	/**
     * <p>
     * Hashes the given plain text using the MD5 algorithm.
     * </p>
     * 
     * <p>
     * Example:
     * </p>
     * 
     * <p>
     * 098f6bcd4621d373cade4e832627b4f6
     * </p>
     * 
     * @param input
     *            The raw input which must be hashed.
     * @return A String representing the MD5 hashed output.
     */
    public static String hashInputMD5(String input)
    {
        String rv = null;
          
        if (input != null)
        {
            try
            {
                // Hash the user ID
                byte[] hashBytes = null;
                MessageDigest md = MessageDigest.getInstance("MD5");
                  
                synchronized (md)
                {
                    hashBytes = md.digest(input.getBytes());
                }
                 
                // Convert the hashed bytes into a properly formatted String
                if (hashBytes != null)
                {
                    StringBuilder sb = new StringBuilder();
                    
                    for (byte b : hashBytes)
                    {
                        String hexString = Integer.toHexString(0x00FF & b);
                        sb.append((hexString.length() == 1) ? "0" + hexString
                                                           : hexString);
                    }
                         
                    rv = sb.toString();
                }
            }
            catch (NoSuchAlgorithmException exception)
            {
                // This exception should never occur
            }
        }
         
        return rv;
    }
    
    /**
     * <p>
     * Hashes the given plain text using the SHA-1 algorithm.
     * </p>
     *
     * <p>
     * Example:
     * </p>
     *
     * <p>
     * a94a8fe5ccb19ba61c4c0873d391e987982fbbd3
     * </p>
     *
     * @param userId
     *            The raw input which must be hashed.
     * @return A String representing the SHA-1 hashed input.
     */
    public static String hashInputSHA1(String input)
    {
        String rv = null;
          
        if (input != null)
        {
            try
            {
                // Hash the user ID
                byte[] hashBytes = null;
                MessageDigest md = MessageDigest.getInstance("SHA1");
             
                synchronized (md)
                {
                    hashBytes = md.digest(input.getBytes());
                }
              
                // Convert the hashed bytes into a properly formatted String
                if (hashBytes != null)
                {
                    StringBuilder sb = new StringBuilder();
              
                    for (byte b : hashBytes)
                    {
                        String hexString = Integer.toHexString(0x00FF & b);
                        sb.append((hexString.length() == 1) ? "0" + hexString
                                                           : hexString);
                    }
                 
                    rv = sb.toString();
                }
            }
            catch (NoSuchAlgorithmException exception)
            {
                // This exception should never occur
            }
        }
             
        return rv;
    }
}

AndroidManifest.xml

If you don’t specify the correct permissions for your app and try to do things like make an HTTP request or grab the Device ID, you’ll get an error, like this:

10-02 15:06:49.223  7776  7784 W System.err: java.lang.SecurityException: Requires READ_PHONE_STATE: Neither user 10109 nor current process has android.permission.READ_PHONE_STATE.
10-02 15:06:49.223  7776  7784 W System.err: 	at android.os.Parcel.readException(Parcel.java:1322)
10-02 15:06:49.223  7776  7784 W System.err: 	at android.os.Parcel.readException(Parcel.java:1276)
10-02 15:06:49.223  7776  7784 W System.err: 	at com.android.internal.telephony.IPhoneSubInfo$Stub$Proxy.getDeviceId(IPhoneSubInfo.java:150)
10-02 15:06:49.231  7776  7784 W System.err: 	at android.telephony.TelephonyManager.getDeviceId(TelephonyManager.java:216)
10-02 15:06:49.231  7776  7784 W System.err: 	at com.yourCompany.yourProjectName.JavaClass.GetDeviceId(JavaClass.java:44)
10-02 15:06:49.231  7776  7784 W System.err: 	at com.unity3d.player.UnityPlayer.nativeRender(Native Method)
10-02 15:06:49.231  7776  7784 W System.err: 	at com.unity3d.player.UnityPlayer.onDrawFrame(Unknown Source)
10-02 15:06:49.231  7776  7784 W System.err: 	at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1363)
10-02 15:06:49.231  7776  7784 W System.err: 	at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1118)

I grabbed the default one from inside Unity.app on my Mac:

/Applications/Unity/Unity.app/Contents/PlaybackEngines/AndroidDevelopmentPlayer/AndroidManifest.xml

Kept all as is, just added my permissions and it worked:

<?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.unity3d.player"
	android:installLocation="preferExternal"
    android:versionCode="1"
    android:versionName="1.0">
    <supports-screens
        android:smallScreens="true"
        android:normalScreens="true"
        android:largeScreens="true"
        android:xlargeScreens="true"
        android:anyDensity="true"/>

    <application
		android:icon="@drawable/app_icon"
        android:label="@string/app_name"
        android:debuggable="true">

        //...

    </application>

	
	<!-- PERMISSIONS -->
		<uses-permission android:name="android.permission.INTERNET"/>
		<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
		<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
	
</manifest>

Some Other Possible Errors

Here’s a fun one, based on a dumb mistake I made. I put the libjni.so into the wrong folder, /Assets/Plugins/, instead of /Assets/Plugins/Android/:

10-02 14:43:17.147  7587  7596 E Unity   : Unable to find jni
10-02 14:43:17.147  7587  7596 E Unity   : Unable to find jni
10-02 14:43:17.155  7587  7596 E Unity   : Unable to find jni
10-02 14:43:17.163  7587  7596 E Unity   : Unable to find jni
10-02 14:43:17.171  7587  7596 E Unity   : Unable to find jni
10-02 14:43:17.171  7587  7596 E Unity   : Unable to find jni
10-02 14:43:17.179  7587  7596 E Unity   : Unable to find jni
10-02 14:43:17.186  7587  7596 E Unity   : Unable to find jni
10-02 14:43:17.897  1410  1410 I wpa_supplicant: WPS-AP-AVAILABLE 
10-02 14:43:17.905  1320  1411 V WifiMonitor: Event [WPS-AP-AVAILABLE ]
10-02 14:43:17.905  1320  1411 D WifiMonitor: WPS Event: WPS-AP-AVAILABLE 
10-02 14:43:18.264  1391  1391 D RadioSignalLevel: evdo dbmLevel: 4, snrLevel: 3
10-02 14:43:18.522  7587  7596 I Unity   : DllNotFoundException: jni
10-02 14:43:18.522  7587  7596 I Unity   :   at (wrapper managed-to-native) JavaVM:AttachCurrentThread ()
10-02 14:43:18.522  7587  7596 I Unity   :   at MyUnityDeviceIdScript.Start () [0x00000] in <filename unknown>:0 
10-02 14:43:18.522  7587  7596 I Unity   :  
10-02 14:43:18.522  7587  7596 I Unity   : (Filename:  Line: -1)
10-02 14:43:18.522  7587  7596 I Unity   : 
10-02 14:43:21.561  7587  7596 I Unity   : checkDeviceID() called
10-02 14:43:21.561  7587  7596 I Unity   :  
10-02 14:43:21.561  7587  7596 I Unity   : (Filename: ./Runtime/ExportGenerated/AndroidManaged/UnityEngineDebug.cpp Line: 43)
10-02 14:43:21.561  7587  7596 I Unity   : 
10-02 14:43:21.671  7587  7596 E Unity   : Unable to find jni
10-02 14:43:21.679  7587  7596 E Unity   : Unable to find jni
10-02 14:43:21.679  7587  7596 E Unity   : Unable to find jni
10-02 14:43:21.679  7587  7596 E Unity   : Unable to find jni
10-02 14:43:21.694  7587  7596 I Unity   : DllNotFoundException: jni
10-02 14:43:21.694  7587  7596 I Unity   :   at (wrapper managed-to-native) JavaVM:AttachCurrentThread ()
10-02 14:43:21.694  7587  7596 I Unity   :   at MyUnityDeviceIdScript.GetUniqueDeviceID () [0x00000] in <filename unknown>:0 
10-02 14:43:21.694  7587  7596 I Unity   :   at MyUnityDeviceIdScript.callTheUrlWithDeviceIDParam () [0x00000] in <filename unknown>:0 
10-02 14:43:21.694  7587  7596 I Unity   :   at GameManager.checkDeviceID () [0x00000] in <filename unknown>:0 
10-02 14:43:21.694  7587  7596 I Unity   :  

As far as I’ve seen, this code only works on a device. If you try to test inside Unity, you’ll get a similar error:

DllNotFoundException: jni
MyUnityDeviceIdScript.Start () (at Assets/Scripts/MyUnityDeviceIdScript.cs:21)

Once you test on a device, if all else if good, this error should go away.

NOTE: looks like this code requires some time to load up the JNI .so file. Not absolutely sure yet, but it appears if I have a fairly complex project and I try to call a JNI related method very soon after app loading, the app crashes with weird mystery output in adb logcat. Need to look into this more to be sure about the details.

Work in Progress: Choices for Mobile Development

Example “every day” app request:

Build me a “recipes” app that lets me browse resipes and take a photo of a dish and upload to Facebook App, Flickr account, Twitter feed, or Generic Server so it can later be displayed in a web view or another in-app view that gets refreshed after you get a “success” message back from the server that you uploaded to.

Right this second, I’d personally code it in Objective-C/Xcode first, then do a Java version for Android.

QUESTION: Given a bit more time and a chance to step back for a minute, which language, IDE, SDK should it be written in?

Near Term Technology Choices

  • Corona SDK
  • Objective-C in Xcode for iOS / Java in Eclipse for Android
  • AIR 3.1 for mobile, CameraUI
  • PhoneGap
  • Titanium

Corona SDK, media.Camera

Cons

  • As of 02.20.2012, lack of support for Web Services (REST, SOAP, etc) processing. So far just HTTP POST & GET and sockets.
  • 2.5D is not easy in Corona SDK. Trying to “fake 3D” or do 2.5D by scaling a physics body while animating it’s position doesn’t work out of the box, for example. Various hacks are required to fake it. While you’re resizing the visual graphic for every frame, collision detection is likely to get screwed up because the physics body’s collision bounding box doesn’t resize “on enter frame” after it’s been set once. This is a Box2D limitation, from what I’ve heard. In general, Corona is best for 2D content only, at least for the moment.

Pros

  • Holy shit! It’s so easy! If you have Actionscript experience (or Javascript application dev experience), Corona is a piece of cake. Feels easier than web Javascript (no DOM differences or old browsers to worry about). Here’s a Flash to Corona porting guide, their pitch to Flash Devs.
  • Has support for device hardware access to Camera (native Camera app can be call up) via media.show().
  • Has access to SQLlite.
  • No iAds support but has custom Ads framework with support for two ad networks.
  • Has built in Physics, Animation, Facebook, Analytics, JSON, In-App Purchases libraries.
  • Looks super approachable for the average AS3 developer. A bit more to learn for Front End devs who’ve never worked with sprite sheets, movieclips, easing equations, etc. Faster for Front End and Flash Developers to learn than learning about reference counting in Objective-C.

Objective-C / Java native, UIImagePickerController or AV Foundation framework / android.hardware.Camera

Cons

  • Building for iOS first (most likely). Will need to write separate Java version for Android. Two code bases to maintain.
  • Possible code base fragmentation between iPhone, iPad 2 and iPad 3, depending on how the app file size download limits issue plays out and whether. People are expecting x4 the pixels for iPad 3 high res display.
  • More dev time required

Pros

  • Closer to the metal, more hands on control of everything in the iOS / Android SDK. Fewer problems, re: lack of full native support in 3rd party mobile tools? (a.k.a. no need to find or write “native extensions”).
  • Cleaner code – just try opening up a published Titanium project in Xcode and take a look at the crap load of native code that converts JS to Obj-C included that would not be there if you built your app using native code in the first place.
  • A lot of clients, for the moment, seem very into iPads and iOS, more so than into Android (not a long term bet, considering Android’s market share, even with the hardware fragmentation).

AIR 3.1 for mobile, CameraUI and CameraRoll

Cons

  • Adobe’s sloppy management of the Flash platform was a highly frustrating and uninspiring series of events. Between the buggy releases of Flash IDE, Flash Builder and the Flash browser plugin, especially on Mac OS X, and Adobe’s bumbling PR fiasco re:HTML5, it’s belated focus on the Gaming market and it’s late introduction of Stage3D for mobile devices Adobe is not a company that inspires me with confidence when it comes to IDE’s and SDK’s for any kind of code.
  • Lack of full native support in 3rd party mobile tools? (need to find or write “native extensions”).
  • Need to super optimize AS3.0 code. Possibly at the expense of code clarity.
  • To get access to the Gyroscope and Notifications, you need to use a Native Extensions
  • Potentially unable to use some commonly used libraries, for example, if they’re not compatible with Starling framework (Stage 3D) etc. or if they’re likely to affect performance on slower mobile processors

Pros

  • There’s a legion of Devs with years of AS3.0 experience out there.
  • Tons of free resources all over the web.
  • I’m getting up to speed w/ Objective-C, have Java experience, how complex will it really be to write my own native extensions?
  • Possibility of a Single Code base for iOS and Android…

PhoneGap

Cons

  • Adobe…
  • Lack of full native support in 3rd party mobile tools? (need to find or write “native extensions” ?).
  • Will still require lots of conditional code / State design pattern to account for platform specific features as well as iPad v. iPhone, standard display v. high retina display, etc.

Pros

  • PhoneGap has some elementary access to the iOS camera (at least).
  • More developers know Javascript, HTML, CSS or at least, those are easier to pick up than manual “reference counting” in Objective-C
  • Support for Web Services via Javascript, examples in their wiki.
  • Possibility of a Single Code base for iOS and Android…

Titanium

Cons

  • Lack of on device debugging in the FREE version of Titanium IDE itself. Looks like there’s a 3rd party tool that might work.
  • Incomplete documentation in Titanium’s API docs. For example, as of 03.19.2012, the Filesystem API doesn’t document methods like mimeType(), which is nontheless included in the Kitchen Sink’s filesystem.js example.
  • Lack of full native API support. Need to find or write modules for certain native features.
  • Will take months for Titanium to be updated for features in every new native OS release (like it did with the iOS 5 release).
  • Will sometimes still require lots of conditional code to account for platform specific features as well as iPad v. iPhone, standard display v. high retina display, iOS v. Android, etc. Perhaps, this is not a surprise, since for Universal apps in Xcode one sometimes has to create separate Views or .xib files for Universal apps, one for iPhone, one for iPad.
  • Titanium IDE was super buggy on my OS X 10.6.8 machines at work and home. SDK 1.8.2 seems to have fixed these issues.

Pros

  • A reasonable level of Memory Profiling is possible for Titanium apps using Xcode’s Instruments.
  • Titanium offers you access to your device’s built-in basic camera app (UIImagePickerController on iOS), but it looks like a lot of the Titanium.Media camera related methods are iOS-only.
  • Enterprise-level support available, which Tech / IT Directors in charge of larger projects will find appealing.
  • Titanium allows developers to write their own modules, if Titanium itself is missing native features. There’s an iOS Module Developers Guide. For example, Titanium doesn’t support the iOS AV Foundation framework, the one that allows you to write your own custom Camera or Video application (as opposed to using UIImagePickerController, etc). Here’s a Titanium AV Foundation module written by a dev on GitHub (free, open source, under Apache License 2.0).
  • Has a Web Services (SOAP) example in it’s demo Kitchen Sink app. More developers already know Javascript.
  • Has iAds support. Possible to use other networks, like AdMob, through plugins/extensions (write yourself or get from their Open Mobile Marketplace)
  • Possibility of a Single Code base for iOS and Android…

Flash Builder & Apparat example: BUILD FAILED “java.io.IOException: Cannot run program “…/mxmlc” (in directory “…/apparat-ant-example”): error=2, No such file or directory

Made sure my Flash Builder 4.5 on OSX 10.5 is set to use Java 1.6 (out of the box it came set to use JVM 1.5).

Followed the instructions on webdevotion.be and cultcreative.com.

When it came time to do “Run As > Ant Build” I kept getting this error:

Buildfile: /your_path_to_example_folder/apparat-ant-example/build/build.xml
clean:
compile:

BUILD FAILED
/your_path_to_example_folder/apparat-ant-example/build/build.xml:64:
Execute failed: java.io.IOException: Cannot run program "/Applications/Adobe%20Flash%20Builder%204.5/sdks/4.5.0/bin/mxmlc"
(in directory "/your_path_to_example_folder/apparat-ant-example"): error=2, No such file or directory

Total time: 860 milliseconds

After trying a bunch of things, it turned out it was a permissions problem.

To fix it, I swapped Flex SDK to one outside of /Applications/ folder. Inside the project’s build.properties I updated FLEX_HOME line to:

FLEX_HOME=/your_path_to_sdk/Flex_SDKs/4.1.0

instead of

FLEX_HOME=/Applications/Flash%20Builder%204.5/sdks/4.5.0

and it worked.

Eclipse links for Android w/ Java

Add Missing Import Statements: Cmd-Shift-O
“An easy way to add import packages to your project is to press Ctrl-Shift-O (Cmd-Shift-O, on Mac). This is an Eclipse shortcut that identifies missing packages based on your code and adds them for you.”

More shortcuts:

Eclipse themes w/dark background & light text

Note to self: Structs in C++ are like Value Objects in Actionscript or Java

Wiser folks than I have accurately pointed out that no analogy is perfect. In this case, it’s plain to see that Structs in C++ are an official data type that’s part of the language itself, whereas Value Objects are more of a convention (former design pattern[1]) created by Java programmers (among others) over the years.

Structs are similar to Value Objects since both are essentially containers for a bunch of data. Both don’t have methods. Perhaps, Value Objects could have Getters & Setters, but more often there aren’t methods.

An example of a Struct in a C++ tutorial:

struct database {
  int id_number;
  int age;
  float salary;
};

int main()
{
  database employee;  
  employee.age = 22;
  employee.id_number = 1;
  employee.salary = 12000.21;
}

An example of a Value Object from an AS3 tutorial using PureMVC:

package com.flashtuts.model.vo
{
	public class DataVO
	{
		public var dataURL:String          = 'assets/xml/data.xml';
		public var urlsArray:Array	  = [ ];
		public var urlsDataArray:Array  = [ ];
	}
}

1. In Java the Value Object Pattern is now called the Transfer Object Pattern.

Adding MySQL to $PATH Environment Variable on OS X

Update, 09.10.2012: This just worked for me for adding Android’s adb tool to my environment path on OS X 10.6.8. The first time I tried I got an error because I wrote “export $PATH=” instead of “export PATH=”.

Earlier this year I took some Java courses. I learned a ton from what was on the syllabus. It was exciting to see stuff like Generics in the Collections framework in JDK 1.5 and compare it to how Actionscript didn’t have that option until very recently, when the Vector class was added to AS3 for Flash Player 10.

One thing that caught me by surprise was that all software installation instructions for class materials were for Windows only (may be I was naive to expect otherwise). The professor was good but he wasn’t a Mac guy and he was super busy at his day job. A few of us OS X guys had to do extra work on our own on top of all the regular class work, just to get Eclipse, Tomcat & MySQL working on our systems. As painful as it was to spend extra days on things like “Why do I have to spend days on learning UNIX when my Java homework is due tomorrow?!!!” OR “Why do I keep getting a 404 Error for Servlets but not for JSP?! !@##$#^$%^$%^!!”… in the end, I think we ended up as slightly better developers, with a little bit more experience, because we all had to teach ourselves a little Terminal and OS X UNIX commands on the spot.

At the very least, I can always say, “Hey, at least I taught myself how to add “mysql” to the $PATH Environment Variable on OS X:

  1. launch Terminal (assuming it’s a bash shell)
  2. write ‘echo $PATH’ to see what your path is now
  3. if ‘mysql’ isn’t in there, write in the path to where you installed it via this command:
    ‘export PATH=/Users/your_user_name/your_path_to_mysql/mysql/bin:$PATH >> ~/.bash_profile’
  4. that should add it to your bash_profile
  5. write ‘echo $PATH’ again, you should see ‘mysql’ in there

Note: this is for installing MySQL as a stand alone app for use with J2EE/Java projects. If you’re just trying to do some PHP on a development machine, it’s easier to use a wysiwyg LAMP package like MAMP or XAMPP.

More on the $PATH environment variable here.

The same technique can be used to add the open source Flex SDK compiler, MXMLC, to your $PATH environment variable on OS X.