10 December 2010

Quick tip: Quick Formatting of Android XML Files

One of the most useful tools in Android's Eclipse plug-in is the Layout Editor. It is easy to experiment with layouts using the drag-and-drop enabled editor without having to worry about the correct syntax or if you are using the correct attribute name.

After creating your layout this way, however, you can end up with a messy XML file. I say "messy" in the sense that elements can run on in one veeeeeeeeeeeery long line, and if you are about to edit the XML file manually, this can be a nightmare.

I used to format the XML file by hand, putting in line breaks and correcting indentation. But one edit using the graphical layout editor and it's messed up again. And then I had a light bulb moment. Eclipse allows auto-formatting of code, but what about XML files? AHA!

It turns out that auto-formatting works for XML files too! Simply select all the contents of the XML file (CTRL-A) and then press the ultra magical shortcut CTRL-I and your XML file is clean and orderly as can be! YAY!

What happened to my layout editor?

There you are, happily creating your layout files in the Eclipse plug-in's layout editor. Dragging and dropping is a breeze. But then one day, you open a layout XML file and boom! No UI! All you see is the XML tree with all the nodes and attributes. What happened?

This happened to me and I was in a panic for a few seconds. Why do things like these have to happen to me? I tried opening a layout file from another project in the same workspace, and it has the UI! What happened?

It probably has something to do with the interpreter you used to open the XML file, a voice in my head said. So I tried right-clicking on the XML file, and lo and behold, I found it. I may have accidentally clicked on some file in one of my mad-clicking moments and changed the setting.

So anyway, to bring back the Layout UI Editor, right click on an XML file > Choose Open With > Android Layout Editor.

I would say that everything is handy dandy, but apparently, the engineers at Google decided that we developers need a little less help and removed the very useful up and down arrow keys in the Outline View when editing XML layouts. Why do they hurt us like this?


11 November 2010

What grammar?

My OC side was alarmed when suddenly, my Problems view in Eclipse was filled with warnings on my XML files. Each of my XML files had a warning with it, and that little yellow exclamation mark on the side:
No grammar constraints (DTD or XML schema) detected for the document

So how do you get rid of it? Go to Window > Preferences > XML > XML Files > Validation then set Indicate when no grammar is specified to Ignore. Click on Apply.

Clean up your project (Project > Clean).

If the problem doesn't go away, you may need to re-validate the XML files. Right click on the file then choose Validate from the popup menu. You can also right click on the folder (such as your res folder) and validate from there.

10 November 2010

TextView and MaxLines

I have a TextView (who doesn't?) and I want to adjust its height automatically, depending on the length of the text it will contain. Should be easy. It was, but it took me a couple of minutes to figure it out.

So I want my TextView to be by default one line tall, but be able to expand up to two lines. My initial set up was to set lines=1 and maxLines=2, but it was making the TextView always two lines. Not what I wanted! I went through the documentation again, read each word carefully, and then:
<TextView android:id="@+id/title"
android:text="This is the text" />
So it turned out that you have to set both minLines and maxLines. TADA!

26 October 2010

Missing hierarchyviewer in SDK 7

If you have SDK version 7, you are most probably missing the hierarchyviewer from your /tools folder. To check your SDK version, launch the SDK manager UI from your installation path, usually C:\android-sdk-windows, then click About.
To run hierarchyviewer, you need to manually create the hierarchyviewer.bat file and add it to your <install_path>/tools directory. The text of the batch file can be copied from here.

And so, you can now run hierarchyviewer as you would if the SDK release isn't effed up. Don't know how to run it? Follow these steps:
a. In Windows, open up a terminal by running cmd.
b. Navigate to your SDK's install path. Since I installed mine in C:\, I would have to type in cd C:\android-sdk-windows\tools
c. Type in hierarchyviewer at the prompt.

15 September 2010

More plurals: decimal values

In my previous post, I showed you how to set string plurals. If you noticed, the methods to get the plurals strings only accept ints. What if (like me) you want to display a decimal value? I am getting my raw value from a progress bar with a range of 1-10, with 0.1 increments.

First, to display decimal values, I set my plurals string to display a float value.
<item quantity="other">Progress is at %.1f units.</item>

And then I devised a way to set the quantity based on the value of the progress bar (ProgressBar.getProgress() returns an int).

public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

// get quantity for plurals string
int quantity = setQuantity(progress);

// convert the actual progress to float
float floatProgress = convertProgress(progress);

// get the actual string and replace formatting with the float value
String currentProgress = getResources()
.getQuantityString(R.plurals.seekBarProgress, // get the plurals
quantity, // set the quantity
floatProgress); // format arguments

// set text to display
TextView displayProgress = (TextView)findViewById(R.id.prog_text);


* Use this method to see if we will use the singular or plural string.
* @param progress
* @return the value to set in getQuantityString()
private int setQuantity(int progress){
int quantity;

if (((progress%10) == 0) && ((progress/10) == 1)){
quantity = 1;
} else {
quantity = 2;

return quantity;

* Use this value to get the *actual* value to display.
* @param progress actual progress value from 0 to 100
* @return the float value from 0.0 to 10.0
private Float convertProgress(int progress){
return ((Float.valueOf(String.valueOf(progress)))/(float)10);
So you see, it's quite long-winded. Here are some screen shots of the results:
Different values for the unit value

String Pluralization

Last week, I discovered Android's support for plural strings by accident. And a good accident it was since I am working on an app that will display a float to the user. I used to display:
You set XX mile(s).
which is kinda lame.

Plurals lets you specify the string to display for different quantities. So how do we use this Plurals thing?

In your string resources XML, which is usually strings.xml, define the plurals element like so:

<?xml version="1.0" encoding="utf-8"?>
<plurals name="pluralsTest">
<item quantity="one">You have one friend.</item>
<item quantity="other">You have %d friends.</item>
Remember, your parent node must be <resources>!

Android provides several methods to use these in your code. Let's see what each of them results to when used:

// set one as the quantity
String one = getResources().getQuantityString(R.plurals.pluralsTest, 1);

// set two as the quantity
String more = getResources().getQuantityString(R.plurals.pluralsTest, 2, 2);

// set one as the quantity
CharSequence quantity = getResources().getQuantityText(R.plurals.pluralsTest, 1);

// set two as the quantity
CharSequence quantityMore = getResources().getQuantityText(R.plurals.pluralsTest, 2);

I created a basic layout with TextViews to display what each of these strings look like. Take note though that getQuantityText() returns a CharSequence and not a String! Also, from what I have noticed, and as the name mildly suggests, getQuantityText() gets the actual value of the text you defined in your xml.

10 September 2010

Importing existing Android projects to Eclipse

When trying to import an existing Android project to Eclipse, I always encounter the error: The method XXXXX must override a superclass method.

At first I was confused. I think this is a Java 1.5 thing, but I am running Java 1.6, and a quick check with my workspace settings show that this is indeed the case. So why the errors?

I searched the intarwebz, and I found out that I am not the only one encountering this! Now I do not want to comment out all the @Override annotations, since it is tedious and would dirty up my code.

Turns out that this is a weird Eclipse behaviour that you can correct with a few simple clicks.

Go to Window > Preferences > Java > Compiler. It should show the compiler compliance level to be 1.6, but the errors are still there. What the frak, Eclipse? Just to be sure, select 1.6 in the dropdown options. This worked for me, but if it doesn't work for you, try the next step.

Click the Configure Project Settings link. It should show a list of the projects in your workspace. Choose your Android project, click OK. Tick the Enable project specific settings box, then choose 1.6 as the compiler compliance level. That should work. :)

It's so fluffyyyyyyyyy!!!

I've created a Minion to join Gru's Minion army.

07 September 2010

Quick string resource formatting

Sooner or later, you would want to display a message to your user with dynamic content. This may be the number of results, the user's name, etc.

Luckily for us, Android provides a convenience method that we can use for such purposes.
public final String getString (int resId, Object... formatArgs)
This means that we can define a string in our strings.xml file with format specifiers supported by Java's formatter class. For example, if I have such a string:
<string name="formatted_string">Hello, %s! You have %d messages.</string>
I can get this string, apply the formatting, and then set it into a TextView without additional processing on my part.
TextView string = (TextView) findViewById(R.id.form_string);
string.setText(getString(R.string.formatted_string, "Zarah", 4));
And I will have this:
Nifty and easy!

Of course, this is a simple example. But I hope you get the drift. Do read the Formatter's documentation to see all possible formats you can use.

06 September 2010

A test, a test

I was thinking of starting a quick-tips style blog for software development (mostly for myself, since I tend to forget stuff a lot recently).

And since I am working on Android now, this would most probably focus on tips and notes on application development for that platform.

And now, I test SyntaxHighlighter.
public void onCreate(Bundle savedInstanceState) {
TextView text = new TextView();
text.setText("Hello, Droid warriors!");