Inheritance, some examples for SCJP study

Inheritance is a practice of one thing extending another. So you can more specific subclasses of a class. Inheritance is available in most programming languages, and in Java it is implied using the extends keyword.

For example, you may have several objects like Car, Boat, Truck, these may all have common behaviour and state between them. You could duplicate the shared members between them, but that can lead to a maintenance nightmare for some poor man in the future. The best option would be too look at inheritance, and try to move common, generic code to a superclass, such as Vehicle.

Then, your subclasses can all extend Vehicle, and automatically inherit the shared members, so you only have them coded once. Inheritance can do down as many levels as you like, and both classes and interfaces can use inheritance (a class can extend another class, and an interface can extend another interface, but never implement it).

In Java, you can only extend a single class at a time, which prevents multiple inheritance that you would otherwise get in another language.

Consider the below sample that I have on my SCJP samples Github project, which portrays a simple inheritance structure:

package com.jameselsey.demo.scjp.oo_concepts;

/**
 * Author:  JElsey
 * Date:    16/08/2012
 *
 * Sample of inheritance, showing a few classes that extend from each other, there is a little bit of polymorphism in here
 * too, can you spot it?
 */
public class Inheritance
{
    public static void main(String[] args)
    {
        Grandfather grandfather = new Grandfather();
        Daddy daddy = new Daddy();
        Son son = new Son();

        // The Grandfather is at the top of the inheritance tree (extends from java.lang.Object), so he only has wisdomLevel
        System.out.println("The grandfather has a wisdom level of " + grandfather.wisdomLevel);

        // The Daddy is strong, and also inherits his wisdom
        System.out.println("The daddy is " + daddy.strengthLevel + " and also gets the grandfathers wisdom: " + daddy.wisdomLevel);

        // The boy is lucky, hes very energetic, but also inherits strength from his dad, and wisdom from his grandfather
        System.out.println("The son is " + son.energyLevel + " and " + son.strengthLevel + " and " + son.wisdomLevel);

        // Inheritance also works on methods too, since they're all part of the same family, we can safely put the
        // family name in the grandfather, both the son and daddy will inherit that method
        System.out.println("Grandfathers surname : " + grandfather.getFamilyName());
        System.out.println("Daddys surname : " + daddy.getFamilyName());
        System.out.println("Sons surname : " + son.getFamilyName());
    }
}

class Grandfather
{
    String wisdomLevel = "Wise";

    public String getFamilyName()
    {
        return "Jones";
    }
}

class Daddy extends Grandfather
{
    String strengthLevel = "Strong";
}

class Son extends Daddy
{
    String energyLevel = "Energetic";
}

Encapsulation; shielding state via the use of accessors

Encapsulation is a fantastic OOP concept of being able to shield class state via the use of accessor methods.

Imagine that you have a class, perhaps called Person. This class will have some form of state, such as name, age, date of birth. These would most likely be stored against reference variables. If you left these publicly available, then anyone who develops against your class can freely access them and assign them to whatever they feel necessary.

Later on, you may like to change the way some of this state is represented, for example you may wish to start storing ages as Strings instead of Integers, if you do that, then anyone who is dependant on your class will now be screaming up and down as you would have broken their code that interfaces with yours, as you’ve changed the data type and it will cause compilation issues for them.

Encapsulation helps protect against these scenarios, whereby you would make the state private so other people can’t access it directly, but at the same time you would provide public methods so that developers can still use your class, and those public methods would access the private state.

This means that if you change your internal representation, you’d just need to update the implementation of the accessor method to retrieve the new data type, convert it to what the old API was expecting, and return it. Developers using your code won’t be interested in how its stored internally provided they can get their data in and out, if you change something behind the scenes, they won’t care (maybe they would, but this is just an example).

By forcing developers to access state via accessor methods, you can also enforce other restrictions like validation, without encapsulation the developers could put any value into name, and there is nothing you could do about it. However, using accessor methods, you could check the value beforehand and see that it meets your requirements, if it doesn’t, throw an exception.

Encapsulation is generally perceived to be good practice, and you should try to use it where possible. Some languages, such as Groovy even implement this out of the box for you, unless you state otherwise.

Please consider this example from my SCJP samples Github project, which displays the basics of encapsulation:

package com.jameselsey.demo.scjp.oo_concepts;

/**
 * Author:  JElsey
 * Date:     16/08/2012
 *
 * Demonstrating an understanding of the Encapsulation OOP term, which basically means to shield instance behaviour
 * behind publicly accessible accessors, thus giving more control of the internal representation of the values
 * and provides a single point of access.
 */
public class Encapsulation
{
    public static void main(String[] args)
    {
       // Create a class that doesn't use encapsulation

        UnencapsulatedMess mess = new UnencapsulatedMess();
        mess.personName = "James";
        mess.personAge = 26;
        System.out.println(mess);

        // now create a similar class, but one which implements encapsulation, notice the use of the accessor methods
        // rather than direct variable access
        EncapsulatedDream dream = new EncapsulatedDream();
        dream.setPersonName("James");
        dream.setPersonAge(26);
        System.out.println(dream);


        // Now, lets create another mess, but this time we want to have some control over what values the variable takes
        UnencapsulatedMess anotherMess = new UnencapsulatedMess();
        String someNameThatWouldComeFromAnotherClass = "Daniel";
        int anAgeThatWouldComeFromAnotherClass = 12;
        if (anAgeThatWouldComeFromAnotherClass < 16 || anAgeThatWouldComeFromAnotherClass > 60)
        {
            // handle an error
        }
        else
        {
            anotherMess.personAge = anAgeThatWouldComeFromAnotherClass;
            anotherMess.personName = someNameThatWouldComeFromAnotherClass;
        }
        // Woah! A lot of waffle to validate a value before we place it, and whereever you refer to this unecapsulated
        // class, you'd have to do the same thing, and how easy that would be to get wrong or be inconsistent!

        // With the encapsulated class, you could do all your validation in a central place, and be sure it is ALWAYS invoked,
        // This may not be the BEST place to validate, but its just an example of the benefits of encapsulation.
    }
}


class UnencapsulatedMess
{
    public String personName;
    // no access modifier specified, so takes default
    int personAge;

    @Override
    public String toString()
    {
        return "UnencapsulatedMess{" +
                "personName='" + personName + '\'' +
                ", personAge=" + personAge +
                '}';
    }
}

class EncapsulatedDream
{
    // make the state private, so only accessible within the class itself.
    private String personName;
    private int personAge;

    // Accessors
    public String getPersonName()
    {
        return personName;
    }

    public void setPersonName(String personName)
    {
        this.personName = personName;
    }

    public int getPersonAge()
    {
        return personAge;
    }

    /**
     * Another useful utlitly method that encapsulation aids with, returning the person
     * age as a user friendly, readable String.
     * @return String the persons age as a String
     */
    public String getPersonAgeAsString()
    {
        return personAge + " years old";
    }

    /**
     * This is an accessor method to set the persons age, this method also performs some validation
     * on the value being set
     * @param personAge int the persons age, in years
     */
    public void setPersonAge(int personAge)
    {
        if (personAge < 16 || personAge > 60)
        {
            // Do something here! Throw an exception or log something
        }
        else
        {
            this.personAge = personAge;
        }
    }

    @Override
    public String toString()
    {
        return "EncapsulatedDream{" +
                "personName='" + personName + '\'' +
                ", personAge=" + personAge +
                '}';
    }
}

Overloading in Java, what it is and how you can use it, along with some examples

There are times when developing, when you need to do similar behaviour but with differing input arguments, for example you may have a method that prints something to the console. You may need to print Strings, Integers, and all sorts of other objects. You could (if you really wanted), create a method for each one with some kind off suffix, such as printString(), printInteger(), printMyObject(), however there is a much neater way of doing this, called overloading.

Overloading basically allows you to reuse the method name multiple times, providing you supply a different number and type of input arguments for each one, so that the compiler can tell them apart. This means we can have methods like print(String string), print(Integer integer) and print(String string, Integer integer), this makes code structure a lot neater and is generally considered good practice.

This is quite different to overriding, and you need to be careful not to get the two mixed up, you may be interested in a previous post where I compared the two.

This is one example of overloading that I have up on my SCJP examples Github project :

package com.jameselsey.demo.scjp.oo_concepts;

/**
 * Author:  JElsey
 * Date:    17/08/2012
 *
 * A simple demonstration of what Overloading is and how it can be used. Overloading allows you to have a method with the same
 * name, but overloaded with differing arguments, this is applicable to methods and constructors
 */
public class Overloading
{
    public static void main(String[] args)
    {
        Overloading ol = new Overloading();

        // Same method name, but overloading with differing input arguments
        ol.sayAboutAPerson();
        ol.sayAboutAPerson("James");
        ol.sayAboutAPerson("James", 26);

        // now lets instantiate an object using overloaded constructors
        Person p1 = new Person();
        Person p2 = new Person("James");
        Person p3 = new Person("James", 26);
        System.out.println(p1);
        System.out.println(p2);
        System.out.println(p3);
    }

    public void sayAboutAPerson()
    {
        System.out.println("We don't know anything about this person");
    }

    public void sayAboutAPerson(String name)
    {
        System.out.println("Persons name is " + name);
    }

    public void sayAboutAPerson(String name, int age)
    {
        System.out.println("Persons name is " + name + " and age is " + age);
    }
}

class Person
{
    String name;
    int age;

    // Look! We can overload constructors too, particulary helpful if you want the flexibility to
    // instantiate objects using a variety of arguments
    public Person()
    {

    }

    public Person(String name)
    {
        this.name = name;
    }

    public Person(String name, int age)
    {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString()
    {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Basics of the switch statement in Java

If statements are great, but sometimes they are just not very practical when you have to test for more than a handful of conditions, have a look at this very poor example of how you build up a long set of if-else statements, its fine for a few checks, but if you’re doing multiple equality checks on a value, its best to use a switch statement for flexibility and readability:


public class PoorIfStatement
{
    public static void main(String[] args)
    {
        int myInt = 5;

        if (myInt == 1)
        {
            System.out.println(myInt);
        }
        else if (myInt == 2)
        {
            System.out.println(myInt);
        }
        else if (myInt == 3)
        {
            System.out.println(myInt);
        }
        else if (myInt == 4)
        {
            System.out.println(myInt);
        }
        else if (myInt == 5)
        {
            System.out.println(myInt);
        }
        else
        {
            System.out.println("Unexpected number...");
        }
    }
}

Now, lets have a look at the same example, but using a switch statement instead, looks cleaner huh?

public class CaseStatements
{
    static int myInt ;

    public static void main(String[] args)
    {

        myInt = 2;

        switch(myInt)
        {
            case 1:
                System.out.println("first");
                break;
            case 2:
                System.out.println("second");
                break;
            case 3:
                System.out.println("third");
                break;
            case 4:
                System.out.println("fourth");
                break;
            case 5:
                System.out.println("fifth");
                break;
            default :
                System.out.println("Unexpected number...");
        }

    }
}

Before we grab our coats and get ready to run, there is a lot more to the switch statement than a mere alternative to a set of ifs, the switch statement can execute more than one case statement! The program will read down from the top of the switch block, and as soon as it finds a suitable match, it will drop in and start processing whatever it finds. Think of it a little bit like a penny machine, the program is looking down the switch block, trying to find one which its penny will fit in, once it does, it pushes the penny in and it drops all the way down. That’s a little strange analogy of it, but its a good one to remember.

It is important to note, that like the above example, if you put in a break statement, then the program will exit out at that point, and not execute any further statements, this is great for if you need to one case statement and not “this case statement and then everything else below me”.

A lot nicer to read isn’t it? And what is better, it is much more flexible. If you need to check for additional conditions, you just need to add a case statement and specify what to do.

Don’t forget, that you can use the default block to catch conditions that don’t specifically match any of the cases, typically you’d put this at the bottom.

Here is another set of examples, that are available up on my SCJP code snippets on Github:

package com.jameselsey.demo.scjp.flow_control;

/**
 * Author:  JElsey
 * Date:    07/08/2012
 *
 * Toying around with the Switch statement a little, running on Java 1.6 so not using switch on Strings yet.
 */
public class SwitchStatement
{
    enum Animals
    {
        CAT, DOG, FISH
    }

    public static void main(String... args)
    {
        switchOnInt(5);
        switchOnInt(0);
        switchOnInt(2);
        switchOnInt(3);

        switchOnChar('a');
        switchOnChar('b');
        switchOnChar('c');
        switchOnChar('d');
        switchOnChar('A');
        switchOnChar('g');

        switchOnEnum(Animals.CAT);
        switchOnEnum(Animals.DOG);
        switchOnEnum(Animals.FISH);
    }

    /**
     * This method switches on an int, notice the (1+2) which is evaluated to 3. Also note no appearance
     * of the break statement in the 3rd block, so default will be execute in addition to 3
     *
     * @param theInt int
     */
    public static void switchOnInt(int theInt)
    {
        System.out.println("\n\nAssessing int :" + theInt);
        switch (theInt)
        {
            case 1:
            {
                System.out.println("The int was 1");
                break;
            }
            case 2:
            {
                System.out.println("The int was 2");
                break;
            }
            case (1 + 2):
            {
                System.out.println("The int was 3, and we're not going to break here either");
                //break;
            }
            default:
            {
                System.out.println("This is the default");
            }
        }
    }

    public static void switchOnChar(char theChar)
    {
        System.out.println("\n\nAssessing char : " + theChar);
        switch (theChar)
        {
            case 'a':
            {
                System.out.println("The char was a");
                break;
            }
            case 'b':
            {
                System.out.println("The char was b");
                break;
            }
            case ('c' | 'd'):
            {
                System.out.println("The char bitwised to make g");
                break;
            }
            default:
            {
                System.out.println("The char didn't match anything, must be something else");
            }
        }
    }

    public static void switchOnEnum(Animals theAnimal)
    {
        System.out.println("\n\nAssessing Animal :" + theAnimal);
        switch (theAnimal)
        {
            case CAT:
            {
                System.out.println("The Animal was CAT");
                break;
            }
            case DOG:
            {
                System.out.println("The Animal was DOG");
                break;
            }
            default:
            {
                System.out.println("The animal was something other than CAT or DOG");
            }
        }
    }
}

Asserting for a Toast message using Robolectric

I’ve recently put together a few proof of concept applications, and since they’re “rough and ready” applications, a lot of the functionality is actually mocked, or given a stubbed implementation.

For example, I’ve got various buttons for things like “sign in with LinkedIn” or “Connect with Facebook”. Since its just a proof of concept, and those features aren’t really must haves, I stub them with a Toast message saying something along the lines of “feature not yet implemented”.

This gives the user the opinion that the buttons are there, functional, however the actions they take are not yet implemented.

This is fine, however if you have numerous stubbed toast messages across the application, or even real toast messages that you have in production standard code, you’ll want to unit test those to be sure you don’t introduce defects when you’re busy beavering away in other areas of the source code.

Fortunately we can use the Robolectric framework to cover a lot of these unit tests. I won’t go into detail about Robolectric here, so please head over to their site and have a look at the basics before you can understand this post.

The assertion is pretty straight forward, and consists of the following :

@Test
public void assertValidationFailureWithNullInput()
{
	searchEditText.setText(null);
	searchButton.performClick();

	ShadowHandler.idleMainLooper();
	assertThat( ShadowToast.getTextOfLatestToast(), equalTo("Please enter a value."));
}

What I have here, is an EditText that I use for a search button, I set its value to null and then click on it. The purpose of the test is to ensure that submitting “search” with a null input will be caught by my validation, and a toast message prompting the user to enter valid data.

Hope that helps, and if you have any questions please leave a comment :)

How to add a splash screen to your android application in under 5 minutes

Adding a splash screen to your application is a quick and easy way to make it look more well rounded, complete, and more professional, it can also serve as a useful distraction whereby you have an extra few seconds to initialise your application components before displaying them to the user.

In this post I’ll show you how to quickly and easily add a splash screen into your application, I’ll also show you how you can create an option whereby users may disable or enable the splash screen for subsequent launches of your application. I’ll also post up my sample code freely on Github so you can checkout what I’ve done and use as you please.

So lets get started right away and create the application, we’ll go ahead and create 3 activities as detailed below, and also shut off the title bar.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.jameselsey.android.demo.androidsplashscreen"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar">
        <activity android:name="SplashActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="MainActivity"
                  android:label="@string/app_name">
        </activity>
        <activity android:name="EditPreferences"
                android:label="@string/app_name">
        </activity>
    </application>
</manifest>

The Splash activity will be the activity that handles the splash screen (Oh, really?!). Since we want to intercept any user launches of the application, we’ll make this the main entry point.

public class SplashActivity extends Activity
{
	// Set the display time, in milliseconds (or extract it out as a configurable parameter)
	private final int SPLASH_DISPLAY_LENGTH = 3000;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.splash);
	}

	@Override
	protected void onResume()
	{
		super.onResume();
		SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
		// Obtain the sharedPreference, default to true if not available
		boolean isSplashEnabled = sp.getBoolean("isSplashEnabled", true);

		if (isSplashEnabled)
		{
			new Handler().postDelayed(new Runnable()
			{
				@Override
				public void run()
				{
					//Finish the splash activity so it can't be returned to.
					SplashActivity.this.finish();
					// Create an Intent that will start the main activity.
					Intent mainIntent = new Intent(SplashActivity.this, MainActivity.class);
					SplashActivity.this.startActivity(mainIntent);
				}
			}, SPLASH_DISPLAY_LENGTH);
		}
		else
		{
			// if the splash is not enabled, then finish the activity immediately and go to main.
			finish();
			Intent mainIntent = new Intent(SplashActivity.this, MainActivity.class);
			SplashActivity.this.startActivity(mainIntent);
		}
	}
}

In the onCreate we’re initialising the view layout, in my case I’m just referring to the splash view which has just a simple ImageView, but yours could contain anything such as images, text, adverts, possibly even combine it with a ProgressBar.

In the onResume, which is invoked after the create, we’re attempting to retrieve a saved variable, defaulting to true if it is not currently set.

A simple check on that boolean decides whether we should spawn a handler with a pre-defined delay, or finish the activity and move onto the main. In either case, we always want to call finish on the splash activity so that the activity is destroyed safely and the user cannot return back to it, then we create an intent to MainActivity and start it.

Arguably, there is more than one way of achieving this, we could use an AsyncTask, or even just spawn off a raw Thread, but I find the handler approach is much cleaner for this task whereby we can use an anonymous inner class rather than a regular inner class, also we don’t need any of the hooks into the UI which the AsyncTask provides, I deem that slightly overkill for such scenario.

That will pretty much get you a splash screen, now lets improve this a little by letting the user disable if they want.

First task we need to do is allow the use of the “menu” button on the device, by adding an override on onOptionsItemSelected in the MainActivity (or anywhere we want to allow this behaviour)

public class MainActivity extends Activity
{
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.options_menu, menu);
		return true;
	}

	/**
	 * This method will be called any time a user selects one of the options
	 * on the menu. For the implementation, whichever button is clicked is
	 * mapped onto the relevant activity.
	 * @param item MenuItem
	 * @return boolean
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
			case R.id.preferences:
				startActivity(new Intent(this, EditPreferences.class));
				return true;
			default:
				return super.onOptionsItemSelected(item);
		}
	}
}

Of course we also need to create the EditPreferences activity too, which in all fairness, exists purely to load preferences from an XML resource file :

public class EditPreferences extends PreferenceActivity
{
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void onResume()
	{
		super.onResume();
		addPreferencesFromResource(R.xml.preferences);
	}
}

Adding the following shared preference :

<PreferenceScreen
        xmlns:android="http://schemas.android.com/apk/res/android">
    <CheckBoxPreference
            android:id="@+id/isSplashEnabled"
            android:key="isSplashEnabled"
            android:title="Splash screen enabled"
            android:summary="Select to enable the splash screen on application startup"
            android:defaultValue="true"/>
</PreferenceScreen>

That is all you need to do! I’ve intentionally left out some of the layout resource files, but you can look them all up on the Github entry I created.

Hope that helps, any comments or suggestions please let me know!

Top 10 Techie things I want to achieve in 2012

I’m not the type of person that gets bored easily, I’ve always got many things to keep me amused, mostly side projects at home. I’m a firm believer, that if you don’t set yourself goals in the first place, then you won’t have anything to fail to achieve, so I’ve set myself a list of targets that I’d like to achieve in 2012 knowing full well I probably won’t get around to them all, but if I can do at least 3, it was worth it.

SCJP

I first picked up the SCJP study guide sometime around 2008, and I’ve had a love-hate relationship ever since. It’s by no means a trivial read, in fact, over 800 pages of solid technical details, a fair chunk of which I’ve never actually used, and probably never will once I’ve got through the exam. Reading the book is not enough to get through the exam, you also need to spend countless hours writing small code snippets to back up understanding, and spend plenty of time in mock exam simulators to prepare yourself. I have a terrible habit of getting obsessively involved in studying for a few weeks, before something pops up (working extra hours on a recent project at work is one good example) and I’ll not touch the book for weeks, only to have to re-cover the chapter where I last left off. This is definitely my goal for 2012, if I achieve nothing else but this, I’d be contempt.

Update AndroidSam

I put my first android app out on the market earlier this year, since its release I’ve had some fantastic feedback, amassing well over 15,000 downloads in the first 6 months alone. The app was very much an experimentation, and I certainly cut a few corners in the UI department prior to launch. I’ve been working on a few look and feel improvements, and a few other tweaks that I’d like to get out there soon.

Become more active on JR and SO, and java black belt

This is a must, theres no end goal and its more of an ongoing task that I must do. StackOverflow is a technical Q&A site, I’ve mostly become involved on the questions asking side, but the site has almost doubled in size in recent years so now there are plenty of unanswered questions that I can sneak in answers to, so I’ll have to start sweeping through my tags and get answering. JavaRanch is also a great site, I read this daily, however I rarely leave any posts. I’m planning to get more active and try to chip in with my comments more often. JavaBlackBelt is yet another great site, I was invited to be a beta question creator on the android exam but I just didn’t get round to providing any content, perhaps I can get more involved in 2012.

Complete SCJP study write ups

I found that a good way to help remember topics when studying, was to try and blog about them. I took the index of the SCJP study guide and outlined all the topics, and then gradually made my way through them all blogging about them in my own words. When trying to explain something, you often realise how you know (or sometimes how well you don’t know a particular subject). I’m about halfway through, and I’d really like to complete the blog posts, and get as much of my sample code up onto my Github account so it can help others.

Read, digest, and blog about technical books

Books, I’ve got a whole shelf of books that need some time. The main 3 that I’m interested in reading in 2012 are Effective Java, Clean Code, and Pragmatic Programmers Guide.

Effective Java is basically a compilation of tips and tricks that a Java developer should use if at all possible, Clean Code tells you how you should be writing your code and approaching problems, and the Pragmatic Programmers Guide is just more theory to lay on top. They’re not trivial reads, and some of it may possibly be too advanced for me, but if I can take anything away from it, it should help my progression.

Finish off my other android projects

I’ve been using Evernote to brain dump app ideas, its a handy little tool. Sometimes you get ideas spring into mind at the most awkward of moments, but most of the time I have my phone to hand, so I just tap them into evernote and let my ideas develop. Right now, in my cooking pot of ideas, I’ve got about 6 apps that I feel are worth putting to code, most are utlitlies but I have a few heavyweight ideas in there. Hopefully I can progress these throughout the year and get at least a few out to market.

Explore Spring Web MVC

The first company that I worked at solely produced Java web applications, that was where I got my first taste for the likes of Struts, Stripes, and a little bit of Spring MVC. I particularly liked working with the Stripes MVC framework, but it did lack a lot of community support, I’d like to explore a little with Spring MVC, since it’s always handy to know how to use the basics of Spring anyway. I started writing my own sales tracking system on Google App Engine, perhaps I’ll do something similar with Spring MVC and host it in the cloud somewhere.

Complete a cloud based CI environment

I’ve got various little side projects on the go, sometimes I use my windows PC at home to work on them, sometimes my works laptop, or my linux machine, so it can be a bit of a pain managing source code and builds. Fortunately I discovered something called Unfuddle, an online SVN repository where I could check my code into. I’ve also discovered something called CloudBees, which is a free on-line Jenkins installation, I’m planning to use that to build all my projects in the cloud, and dump artefacts onto DropBox. I may look at maven repositories too. Ultimately, I want to get my build processes in the cloud, so its purely coding that happens outside the cloud.

Ubuntu Certification

OK so one certification in the year is optomistic, but what about two? I’ve been an on-off linux user since I was in college, only really dipping back into Windows when I go through phases of gaming (WINE is just too much effort). Being competent with the shell terminal is going to help in the long run, so why not dedicate some time to skilling up in something useful. I’m not sure if I’d specifically go for the UCP, but it seemed an obvious choice since I have some familiarity with Ubuntu.

Explore Android ICS

With the latest Ice Cream Sandwich android released, theres plenty to be experimenting with, even if theres only a handful of devices that support it. I imagine that ICS will become more and more supported as the year goes on, so its probably time for me to devote some hours into picking up the new features of the SDK, and coming up with something nice. I’m also desperately in need of upgrading my 2.1 Orange San Francisco sub £100 handset, so possibly an excuse for a nice new shiny upgrade?

Revisit GAE Sales Tracker

About 2 years back I began working on an open source sales tracking system, to monitor progression of sales prospects. I started this in Stripes MVC framework and deployed to the Google App Engine. At the time GAE was still in its infinacy, but after a few years and several upgrades, I think developing on this platform may be slightly less painful now. I still have all the source code, and still have a running demo, maybe I can pick it up again and see what GAE improvements have come around.

Automating android application signing and zipaligning with maven

This is something that has had me tearing my hair out for a few days now, I was pretty much border-line braveheart-ing my screen….

Code rage

I’ve recently been on a little drive to try to maven-ize my projects. All had been going well until I needed to sign and zipalign my APKs. This post will help you conquer that barrier with the use of some maven plugins.

When using ant, I was able to simply enter keystore details into build.properties and just call “ant release”. Unfortunately that approach doesn’t carry across to maven, and you have to provide some more configuration.

Firstly, before we go any further, I’m going to assume that you already have a maven android project setup, so you have a pom.xml, you’ve configured the maven-android-plugin and you can run “mvn clean install” to build your APK, and “mvn android:deploy” to deploy it to an emulator. If you haven’t got that far, I’d suggest you have a look at one of my previous posts to help get you up to speed.

So, when you want to build your application with maven, you’d run “mvn install”. That will, by default, use a debug key to sign your APK. When we want to build a releasable APK we still want to execute the same install goal, however we’ll want to use a proper key. Luckily, maven provides something called profiles.

In short, maven profiles allow you to still perform the same standard goals, yet they behave slightly different, in the manner of binding extra steps to them, all will come clearer in a moment.

This has already been covered, in a useful post by the guys at Novoda, and various other blog posts scattered around the web. I’ve followed at least 10 tutorials and each time I was unable to get the signing process to work correctly, each time I encountered the following error :

INFO] jarsigner: attempt to rename C:\android-projects\jameselsey_andsam_branch_mavenbranch\target\LanguageSelection-1.0.0-SNAPSHOT.jar to C:\android-projects\jameselsey_ands
am_branch_mavenbranch\target\LanguageSelection-1.0.0-SNAPSHOT.jar.orig failed
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Failed executing 'cmd.exe /X /C "C:\development\tools\Java\jdk1.6.0_20\jre\..\bin\jarsigner.exe -verbose -keystore my-release-key.keystore -storepass '*****' -keypass '
*****' C:\android-projects\jameselsey_andsam_branch_mavenbranch\target\LanguageSelection-1.0.0-SNAPSHOT.jar mykeystore"' - exitcode 1
[INFO] ------------------------------------------------------------------------

I’d tried everything, even copying out the command and pasting into a command window worked, but I could not get it to work from maven. Unfortunately it seems there may be an issue with the maven-jarsigner-plugin (as suggested in the comments on the Novoda post). However fear not, for there is an alternative, the maven-jar-plugin.

The maven-jar-plugin is a similar plugin to the jarsigner plugin, however the signing APIs are now deprecated and it points you to use the (apparently) broken maven-jarsigner-plugin. Using a deprecated API doesn’t particulary concern me in this instance, as its just signing artefacts.

Take a look at my profiles section, copy this into your pom.xml :

<profiles>
<profile><!-- release profile. uses keystore defined in keystore.* properties. signs and zipaligns the app to the target folder-->
            <id>release</id>
            <activation>
                <activeByDefault>false</activeByDefault>
            </activation>
            <build>
                <defaultGoal>install</defaultGoal>
                <finalName>${project.artifactId}-${project.version}</finalName>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-jar-plugin</artifactId>
                        <version>2.2</version>
                        <executions>
                            <execution>
                                <id>signing</id>
                                <goals>
                                    <goal>sign</goal>
                                </goals>
                                <phase>package</phase>
                                <inherited>true</inherited>

                                <configuration>
                                    <keystore>
                                        my-release-key.keystore
                                    </keystore>
                                    <storepass>mypassword</storepass>
                                    <keypass>mypassword</keypass>
                                    <alias>mykeystore</alias>
                                    <verbose>true</verbose>
                                    <verify>true</verify>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>

                    <plugin>
                        <groupId>com.jayway.maven.plugins.android.generation2</groupId>
                        <artifactId>maven-android-plugin</artifactId>
                        <inherited>true</inherited>
                        <configuration>
                            <sign>
                                <debug>false</debug>
                            </sign>
                        </configuration>
                    </plugin>

                    <plugin>
                        <groupId>com.jayway.maven.plugins.android.generation2</groupId>
                        <artifactId>maven-android-plugin</artifactId>
                        <configuration>
                            <zipalign>
                                <verbose>true</verbose>
                                <skip>false</skip>
                                <!-- defaults to true -->
                                <inputApk>${project.build.directory}/${project.artifactId}-${project.version}.apk</inputApk>
                                <outputApk>${project.build.directory}/${project.artifactId}-${project.version}-RELEASE.apk
                                </outputApk>
                            </zipalign>

                        </configuration>
                        <executions>
                            <execution>
                                <id>zipalign</id>
                                <phase>install</phase>
                                <goals>
                                    <goal>zipalign</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
</profiles>

OK, so lets walk through what the above profile does. Firstly, the “id” of the profile is “release”, so when you want to apply this profile, you’d run “mvn install -Prelease”. The “activeByDefault” is set to false, which means you need to use the above arguement, if you flip that over, you won’t need the P flag.

The execution goal is to “sign”, which is the API on the plugin, documented here. We bind this execution on to the standard “package” goal. Then we provide the configuration elements which specify the details of the keystore.

In pure English, this binds the plugin phase onto the package goal of maven, so anytime we run using this profile it’ll execute the jar signing of our artefacts. The “verify” tag gives us extra piece of mind by verifying that the signing was successful afterwards.

I’ve also setup a zipalign profile that will take the APK, zipalign it, and rename it to “*-RELEASE.apk”, so I know that particular APK is the one which I’ll release to market.

So thats it, once more a success, and its just one small step on the ladder to android glory!

Phhew!! Done, finally I was able to shutdown the laptop and go to sleep at 3am….on a school night!!!

Good luck, feel free to comment!

Peace.

String concatenation operator

The string concatenation operator is a bit like a hedgehog, it looks cute and sweet, but try to grab hold of it quickly and you’ll soon know about it…

It’s actually quite simple, however there are some traps that are very easily overlooked (just got caught out with it on a mock test, so I’m here to rant).

The rule of thumb is, that if either one of the operands being “+” is a String, then concatenation will occur, but if they are both numbers, arithmetic addition will occur. Sounds simple right? What do you think the following equate to?

package operators;
public class MockTest
{
    public static void main(String[] args)
    {
        System.out.println(3 + 2);
        System.out.println(3 + "s");
        System.out.println("s" + 2);
        System.out.println("hello " + "world");
    }
}

Think you know it? Well its going to be : 5, 3s, s2. The first one is an arithmetic addition, since both sides of the operator are numeric. The second and third are String concatenation, because at least one of them is a String. The fourth one are both Strings, so concatenation once again.

those are the simple ones, however it can get a lot more tricky, have a look at these common ones that those exam creators try to catch you with!

package operators;

public class MockTest
{
    public static void main(String[] args)
    {
        // Inside brackets are evaluated first, so it'll be 7String
        System.out.println( (3 + 4) + "String");

        /* This is the little bugger that caught me, I vouched for 34String, but its actually 7String.
         Concatenation happens from left to right, one at a time, so it'll break it down to:
            3 + 4 then...
            <thing on left> + "String"

         Careful on these ones!
        */
        System.out.println(3 + 4 + "String");

    }
}


So remember, it’ll evaluate from left to right, one “+” operator at a time. Brackets are always evaluated first however.

Take my examples and have a play!

Happy coding (or raging at the screen if the mock tests catch you out…)

The instanceof Operator

The instanceof operator is a great way for checking if a reference variable is of a given type, in other words, does it pass the IS-A inheritance test. Ask yourself, is a Cat a Dog? A Dog a Cat? Or is a Cat an Animal and a Dog an Animal? In true Harry Hill style, there is only one way to decide….FIGHT!!!!

Have a look at my following example :

package operators;

public class InstanceOfOperatorDemo
{
    public static String myString = "James";

    public static void main(String[] args)
    {
        // myString variable is of type String, so returns true
        System.out.println("myString instanceof String : " + (myString instanceof String));
        // Even though myString is a String, a String is actually an Object (extends from Object), so the below is also true
        System.out.println("myString instanceof Object : " + (myString instanceof Object));

        B b = new B();
        // B is technically an instance of the implemented interface, so this should return true
        System.out.println("B instance of Foo : " + (b instanceof Foo));
        // This should return true also for the same reasons as above
        System.out.println("A new A() instance of Foo : " + (new A() instanceof Foo));
        // An A isn't an instance of a B, its the other way around; a B IS-A A, so returns false
        System.out.println("A new A() instance of B : " + (new A() instanceof B));

        // Any checks with null always return false, since null isn't an instance of anything
        System.out.println("null instanceof Object : " + (null instanceof Object));

        int[] myInts = new int[10];
        // Even though this array contains primitives, the array itself is still an Object at heart..
        System.out.println("myInts instanceof Object : " + (myInts instanceof Object));
    }
}

interface Foo {}
class A implements Foo {}
class B extends A {}

As we can see, a String IS-A Object, so that will pass the instanceof test. It is also important to note, that interfaces are also included in the instanceof check, so by checking if a class or a subclass is an instanceof an interface will return true.

Arrays, no matter what they hold, are always objects themselves, so they can be checked for instanceof too, of which they are Objects, as shown above.

It is important to note, that you can’t use instanceof across class hierarchies, this is something they’ll try to trick you out of in the exam, such as comparing a cat against a dog, you can compare up the hierarchy, but not across it, have a look at this example :

package operators;

public class InstanceOfOperatorCrossHierarchyDemo
{
    public static void main(String[] args)
    {
        // a Cat IS-A Dog, plain and simple
        System.out.println("Is cat an instanceof Animal? : " + (new Cat() instanceof Animal));

        // This will fail to compile, since we are not allowed to instanceof check across the
        // object hierarchy, a Cat is not an instance of Dog, so compiler fails
        System.out.println("Is cat an instanceof Dog? : " + (new Cat() instanceof Dog));
    }
}

class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}

That’s it! A nice and easy one, please leave me comments if you can suggest improvements!

Happy coding.