Converting dp to pixels in android

Sometimes in android you have to deal with pixels, which can often be awkward, such as view.setPadding(int, int, int, int).  Obviously this is not ideal as pixel ratings vary from device to device, nonetheless there is a work around for this

Simply come up with the value you want in dip (density independent pixels), such as 10, and then convert into pixels using the display metrics of the device you’re working on. This will ensure that when the conversion runs, it’ll always scale to the device the application is running on.

float sizeInDip = 10f;
int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, sizeInDip, getResources().getDisplayMetrics());

Enjoy!

Top 10 Techie things I want to achieve in 2012

to-do-list-nothing

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.

SMS text messaging simulation on android

sms-incoming
As part of an application I’m currently developing, I need to be able to interogate incoming SMS messages. Since I’ll be developing against the emulator initially I need a way of sending in SMS messages to the emulator. Fortunately, we can use adb to poke in SMS messages at will, as detailed below.
Ultimately, you’ll need to telnet into your emulator, and you’ll need two things:
  • The port the emulator runs on. To find this out, open up a command window and type :

adb devices

You should see something like this :

C:\development\projects\AndroidSam\trunk_androidsam>adb devices
List of devices attached
emulator-5554 device
So my emulator is running on the default port of 5554.
  • Secondly, if you’re a Windows 7 / Vista user, you probably won’t have telnet enabled by default, so switch that on by going into Control Panel > Programs > Programs and Features > Turn Windows features on or off.

Now, lets actually send in an SMS. From the command window, type :

telnet localhost 5554

sms send 07841123123 Hello this is a sample message
OK

Then have a look at your emulator, you should see the SMS come through.
Stick around, I’ll post up some more SMS related tips in the coming weeks!

How to remove the default grey title bar on android apps

Fed up of the default title bar on your android applications?

We can get rid of that easy, either use the following in your activities to do it :

requestWindowFeature(Window.FEATURE_NO_TITLE);

Or, the way I prefer, disable it application wide by slipping the following into the AndroidManifest.xml file :

android:theme="@android:style/Theme.NoTitleBar"

Automating android application signing and zipaligning with maven

Code rage

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.

Compound Assignment Operators

There are various compound assignment operators, however it is only necessary to know the 4 basic compound assignment operators for the exam, being as follows:

  1. += (Addition compound)
  2. -= (Subtraction compound)
  3. *= (Multiplication compound)
  4. /= (Division compound)

Essentially, they’re just a lazy way for developers to cut down on a few key strokes when typing their assignments. Consider the following examples that I’ve created to demonstrate this:

package operators;

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

        // This is the "longhand" way of adding 5 to x
        x = x + 5;
        // You could use the compound assingment as follows, to achieve the same outcome
        x += 5;


        // Lets look at the other 3...
        // This...
        x = x - 1;
        // ...is the same as
        x -= 1;

        // This...
        x = x * 10;
        // ...is the same as
        x *= 10;

        // This...
        x = x / 10;
        // ...is the same as
        x /= 10;

    }
}

That is it! Any suggestions, please let me know!

Happy coding.

Static members…

Statics are a rather strange beast, they belong to no instance of a class, they have no fixed abode, other than their class..

Consider the following example :

package declarations;

public class StaticMembers
{
    private static String message = "hello";
    private String instanceMessage = "hello from the instance!";
    
    
    public static void main(String[] args)
    {
        // You "can" create a new instances and call the static member, but its a bit redundant....
        StaticMembers staticMembers = new StaticMembers();
        System.out.println(staticMembers.message);

        // ..Since you can just call it directly, as statics don't belong to any instances
        System.out.println(StaticMembers.message);
        
        // You can't do this, since how would the static know which "copy" of the instance method to get?
        System.out.println(instanceMessage);
        
        // ..But you can do this, since you have an instance..
        System.out.println(staticMembers.instanceMessage);
        
    }
}

Statics don’t belong to any instance, they belong to the class itself. So there is only ever one copy of a static member (method or variable). Statics can’t ever access an instance variable directly, why not? Think about it, if a static wants to obtain an instance member variable, there may be hundreds, how would it know which one to get? You can however, declare and initialise an instance member from a static, and then access its members, as we’ve done in the example above.

Take my example, and have a play with it, statics are actually quite straightforward once you understand how they behave, but be careful, the exam will try and trick you out with statics accessing instance members directly!

Happy coding!

Local Variables, as far as the SCJP is concerned

Local variables are variables that are declared locally, funny that eh? This one should be nice and easy, lets have a look at a quick example :

package scope.localvariables;

public class LocalVariables
{
    private String instanceString;

    public void doSomething()
    {
        // local variable called 'localS', initialised
        String localS = "hello";
        // Another initialised local variable, with the final modifier so it can't be changed once initialised
        final String localS2 = "hello again";

        localS = "I've changed, since I'm not final";

        System.out.println(localS);
        System.out.println(localS2);
    }

    public void doSomethingElse()
    {
        String localS;
        // Compiler won't like this, since you haven't initialised 's' with anything
        System.out.println(localS);
    }
}

Some really easy things to remember, local variables don’t ever get initialised automatically, so you have to do that yourself. The method above, doSomethingElse, the variable gets declared, but never assigned a value. The compiler won’t assign a default value like it does for an instance varible, so the compiler will complain on the line which tries to print the value to system out. So whatever you do, if you declare a local variable but don’t assign it a value, make sure that you DO assign it a value before you try to use it.

Since variables are declared within a method, they can only be accessed, and actually only live for the duration that method is executing. So if you declare a variable inside a method, but try to access it elsewhere, your code will fail to compile since its scope is only available to the method the declaration resides in. Careful of this one, there are a lot of questions in the exam which will try to catch you out with this!

Local variables can take the final modifier if required, so that once assigned a value it can’t be changed.

Also note, that local variables live on the stack, and not the heap.

Lastly, it is possible to have local variables with the same names as instance variables, this is known as shadowing. You’ve probably seen this countless times before without actually realising, since its quite popular with constructors (with may also have local variables)

package scope.localvariables;

public class MyClass
{
    private String name;
    private int age;

    // Overridden constructor, with 2 local variables that shadow instance variables
    public MyClass(String name, int age)
    {
        this.name = name;
        this.age = age;
    }

    public static void main(String[] args)
    {
        MyClass myClass = new MyClass("James", 25);
        System.out.println("Name is : " + myClass.name + " Age is : " + myClass.age);
    }
}

Thats it, hope you’ve enjoyed the show folks, please leave comments or improvement suggestions!

Thanks!