Friday, August 29, 2008

Why can't there be better checking at compile time!

I am glad that I found out about this little gotcha early on in the piece....

The issue has to do with the difference between @+id and @android:id. The documentation (and Notepad tutorial) don't really give much insight into the difference between the two. I still don't know the difference..

Anyway, when I was following the Notepad V1 tutorial, it gets to step 4 and suggest creating the following file:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<ListView android:id="@android:id/list"
android:layout_width="wrap_content"

android:layout_height="wrap_content"/>
<TextView android:id="@android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:text="@string/no_notes"/>

</LinearLayout>



Notice the android:id="@android:id/list" part. Well, if you use the eclipse layout plugin and add a ListView and TextView using this tool, you don't get "@android:id/list", instead you get "@+id". Surely the two must be equivalent you would think. I happened to notice the difference at the time, but continued on, using the "@+id" format.

After completing the tutorial and getting to the part about running the program, my excitement about seeing my first android application deployed was soon crushed as I got an exception every time I went to deploy it. On I hunch, I change the convention to use the one suggested in the tutorial. To my amazement, it worked the next time I deployed it.

I posted this question on the developer forum and was pleased to get a quick response which I have added below courtesy of Romain Guy:

Hi,

@+id/foo means you are creating an id named foo in the namespace of
your application. You can refer to it using @id/foo. @android:id/foo
means you are referring to an id defined in the android namespace.
This namespace is the namespace of the framework. In this case, you
need to use @android:id/list and @android:id/empty because these are
the id the framework expects to find (the framework knows only about
the ids in the android namespace.)

The XML layout editor doesn't know how you will use your layout and
generates by default ids that are in your application namespace. So
the XML format is correct, it's not a compile time error, but really a
runtime error.

No comments: