Monday, 12 November 2012

A Timer class in Java

Have you ever wanted to time how long it takes to execute a particular section of your code?

Java makes it easy to create a simple class to achieve this.

We want the following things:

  • Tell the timer when to start counting
  • Tell the timer when to stop counting
  • Give us the time elapsed
 Those dot points look like methods to me. Lets write the code:


public class Timer
{
    private long mInitialTime;

    private long mFinalTime;

    public Timer()
    {
        start();
    }

    public void start()
    {
        mInitialTime = System.currentTimeMillis();
        mFinalTime = mInitialTime;
    }

    public String end(String description)
    {
        mFinalTime = System.currentTimeMillis() - mInitialTime;
        return description + ": total time " + getTimeElapsed();
    }

    public long getTimeElapsed()
    {
        return mFinalTime;
    }
}

The timer will start either on object construction or on calling start()

The timer will end when you call end(String) and return a convenient description of how long it took.

If you want the time elapsed in long form, use getTimeElapsed()

Simple as that. :)

Quickly implement constructors based on a superclass in Eclipse

package com.bc.android;

import android.view.View;

public class MyCustomView extends View
{
}


How annoying is it when you inherit from another class and you get this error:

Implicit super constructor View() is undefined for default constructor. Must define an explicit constructor

This means we need to implement at least one of the constructors from the superclass in the subclass.

Turns out Eclipse makes it easy to pick and choose what constructors you want to implement and automatically inserts these constructors into your code.

Open the Source menu and select "Generate Constructors from Superclass..."


Now set a check mark on every constructor you want to implement in your subclass and hit OK.


And there you have it! Three constructors automatically implemented that use the correct parameter list and call the constructor of the superclass.

Here's the final result:


package com.bc.android;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;

public class MyCustomView extends View
{
    public MyCustomView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
    }

    public MyCustomView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    public MyCustomView(Context context)
    {
        super(context);
        // TODO Auto-generated constructor stub
    }
}

How to attach Android source to Eclipse

Don't you hate it when you hit F3 on an Android class and you get Eclipse's ugly class viewer instead of Android's actual source for that class?



There's an easy way to fix it.


In Package Explorer expand your Android library entry (in the case above it's Android 4.1) and right click the android.jar file.

Select Properties...

Fill out the information like I've done here.


In summary, select Java Source Attachment in the left pane.
Mark the External location radio button.
Enter the path of the Android source you've downloaded through the Android SDK Manager.

If you don't have the contents of <android_sdk_location>/sources/<android_version> then you'll need to open your Android SDK Manager and download the source for the appropriate version.

Now next time you want to Open Declaration for an Android class, it'll be in a format that's not going to burn out your eyes. :]

Thursday, 8 November 2012

Referenced Projects and the ClassNotFoundException

You're running an Android application on device or on the emulator through Eclipse.
You get a ClassNotFoundException on a class that's in one of one of your referenced projects.

Well, what now? You can see the file right there. Why doesn't the app have that class?

There's a simple reason for this. It could be one of two issues.

One: You're including a basic Java project to your Android project

The fix:
Open your Android project properties and select Java Build Path in the left pane.
Select the Order and Export tab.
From there make sure that your referenced project has the checkbox enabled. This will put the classes into the final Android .apk file.





Two: You're including an Android library project to your Android project.

The fix:
Open your Android project properties on your Android library project.
Select Android in the left pane.
Make sure the Is Library checkbox is checked.



Open your Android project properties on your Android project.
Select Android in the left pane.
Click the Add... button on the right and select your library project in the dialog.

Now, clean and run your Android app again and no more ClassNotFoundExceptions should appear.

Wednesday, 10 October 2012

Error: Could not find class 'com.woodenhero.android.core.CoreClass', referenced from method com.woodenhero.android.cafebabe.MainActivity.onCreate

Has it happened to you? You're building an Android app with another project on the build path and the app crashes with a stack trace like this:


Could not find class 'com.woodenhero.android.core.CoreClass', referenced from method com.woodenhero.android.cafebabe.MainActivity.onCreate
VFY: unable to resolve new-instance 426 (Lcom/woodenhero/android/core/CoreClass;) in Lcom/woodenhero/android/cafebabe/MainActivity;
VFY: replacing opcode 0x22 at 0x0008
DexOpt: unable to opt direct call 0x0bd5 at 0x0a in Lcom/woodenhero/android/cafebabe/MainActivity;.onCreate


This is how you fix it.


Select your referenced project in Package Explorer and go Project -> Properties

Select Android on the left hand pane

In the Library section, check "Is Library"


Select your app project in Package Explorer and go Project -> Properties

Select Android on the left hand pane

In the Library section, click Add...

Select the app of your referenced project

Click OK then OK again to close the Properties dialog



Clean, compile and run again. You should be good to go.