I post random things I've learned while coding with the hope that it will save people time and effort.
Tuesday, April 10, 2012
Unicode Normalization and Android
I ran into a Unicode rendering issue recently that I wanted to go over. Check out this screenshot from an application we've recently localized into Vietnamese:
Notice how a lot of the text looks cut off (especially those blue labels). What's going on?
It turns out that the TextViews are rendering diacritics improperly. Sometimes the diacritic ends up on the wrong character. Other times, it ends up on its own space. The layout system seems to figure out the width correctly but the renderer screws it up, causing the text to be cut off when layout_width is set to wrap_content. The root of the problem is that Android is messing up combining characters (or combining diacritical marks) in unicode.
The solution that we found was unicode normalization. A character with diacritics can always be represented by a combination of multiple code points, but sometimes there is also a single code point that represents the character. We found that by using unicode's normalization form C (NFC), we could normalize most of the combining diacritical characters out of text (and thus sidestep this problem altogether).
There's two steps we're taking to normalize our text:
1. For all strings that are in our APK, we normalized them inside strings.xml. There are plenty of tools out there (like charlint) that can do the job.
2. We run all strings delivered from servers through Normalizer while parsing. It did not seem to degrade performance to do so.
Step 2 may not be necessary if your app is self-contained and never gets any strings from the net. Also, you could just use Normalizer as your tool for step 1 (it's up to you).
We found this problem to only happen on ICS - it appears to work fine on honeycomb and below. Also, if you want to know more about unicode normalization, I highly recommend reading this article.
Wednesday, April 4, 2012
Yet Another Dumb Widget Hiding Trick
I didn't mean to be writing a series of these articles, but I keep getting backed into a corner...
The last two times, I was dealing solely with preventing app widgets from appearing on particular versions of Android. The problem is that this trick only works for platform version; all other resource qualifiers (like screen size) are ignored.
This becomes a problem when you have a widget that you only want to work on smaller screen sizes, or only in some locales, etc. In this situation, you can't use the AndroidManifest tricks because all those values can change at runtime.
The hackiest answer I found was to manually disable the widget provider on launch, based on whatever parameters you provide. In this case, I'm using a boolean I've defined as "widgetEnabled":
The true answer to this problem is to make sure your widget works on all platforms of Android. But if you're squeezed this hack can save the day as well.
The last two times, I was dealing solely with preventing app widgets from appearing on particular versions of Android. The problem is that this trick only works for platform version; all other resource qualifiers (like screen size) are ignored.
This becomes a problem when you have a widget that you only want to work on smaller screen sizes, or only in some locales, etc. In this situation, you can't use the AndroidManifest tricks because all those values can change at runtime.
The hackiest answer I found was to manually disable the widget provider on launch, based on whatever parameters you provide. In this case, I'm using a boolean I've defined as "widgetEnabled":
public class ExpediaBookingApp extends Application {
@Override
public void onCreate() {
super.onCreate();
if (getResources().getBoolean(R.bool.widgetEnabled)) {
PackageManager pm = getPackageManager();
ComponentName cn = new ComponentName(this, AppWidgetProvider.class);
pm.setComponentEnabledSetting(cn, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
}
}
}
This will only disable the widget after the first launch of the application, so it's still possible for users to install the widget before the first launch. But it's way better than nothing. Also note that this doesn't seem to work on every version of Android (but it does work on ICS, which is what I was targeting).
The true answer to this problem is to make sure your widget works on all platforms of Android. But if you're squeezed this hack can save the day as well.
Tuesday, March 27, 2012
Solving Initial Compilation Issues with Android
Two weeks ago I helped with a beginner's Android Workshop at Mobile March. A lot of the people had problems getting their development environment up and running - but for reasons that weren't really any fault of their own, or were easily overlooked. Typically once you've got all the gears in place building is simple, but I'd forgotten how surprisingly difficult it can be to get a project up and running in Eclipse initially.
Here's a few common problems I saw around the classroom:
- Installing the Android SDK (the tools for Android) but not the ADT plugin (how Eclipse interfaces with the SDK), or vice versa. Make sure both are installed.
- Not installing any Android platforms (or not installing the correct one for the app you're trying to build). The SDK is just a starter package - from there, you need to run the Android SDK Manager and add SDK components. There's an SDK platform for each version of Android; I recommend just installing the whole lot (it takes time to download, but makes everything else easy).
- If you get compilation errors upon importing a project, do a full clean and rebuild. Clean is found in Project --> Clean. This can sometimes clear up import issues.
- Compilation issues with @Override. If you're getting compilation error on @Override, that's because your JDK compliance level is set incorrectly. You either need to go into Eclipse --> Preferences --> Java --> Compiler and set the compliance level to 1.6+, or you need to go into the individual project and change that setting (right-click the project --> Properties --> Java Compiler --> Compiler compliance level).
- Using emulators that are not compatible with your sample app. If your app targets 2.3, you must have a 2.3 (or higher) emulator. If your app uses Google Maps, your emulator must be a "Google APIs" emulator (and also conform to the previous version requirement as well).
- Did you try Android briefly more than a year ago and now it refuses to work? Chances are the problem is an invalid debug.keystore. When you build in Eclipse, it creates your APK using an automatically generated debug keystore. Older versions of Android had these set to expire a year after creation, so if you dabbled in Android before it may have expired. You can find the path to your debug.keystore by going into Preferences --> Android --> Build. You can safely delete your old debug.keystore and the Android build process will automatically create a new, valid one for you.
- If none of the above helps, I found the most useful debugging tool for build errors was to turn on verbose output. You can turn that on in Preferences --> Android --> Build --> Build Output, then check the Console for any salient error messages.
Good luck getting your first Android app building!
Here's a few common problems I saw around the classroom:
- Installing the Android SDK (the tools for Android) but not the ADT plugin (how Eclipse interfaces with the SDK), or vice versa. Make sure both are installed.
- Not installing any Android platforms (or not installing the correct one for the app you're trying to build). The SDK is just a starter package - from there, you need to run the Android SDK Manager and add SDK components. There's an SDK platform for each version of Android; I recommend just installing the whole lot (it takes time to download, but makes everything else easy).
- If you get compilation errors upon importing a project, do a full clean and rebuild. Clean is found in Project --> Clean. This can sometimes clear up import issues.
- Compilation issues with @Override. If you're getting compilation error on @Override, that's because your JDK compliance level is set incorrectly. You either need to go into Eclipse --> Preferences --> Java --> Compiler and set the compliance level to 1.6+, or you need to go into the individual project and change that setting (right-click the project --> Properties --> Java Compiler --> Compiler compliance level).
- Using emulators that are not compatible with your sample app. If your app targets 2.3, you must have a 2.3 (or higher) emulator. If your app uses Google Maps, your emulator must be a "Google APIs" emulator (and also conform to the previous version requirement as well).
- Did you try Android briefly more than a year ago and now it refuses to work? Chances are the problem is an invalid debug.keystore. When you build in Eclipse, it creates your APK using an automatically generated debug keystore. Older versions of Android had these set to expire a year after creation, so if you dabbled in Android before it may have expired. You can find the path to your debug.keystore by going into Preferences --> Android --> Build. You can safely delete your old debug.keystore and the Android build process will automatically create a new, valid one for you.
- If none of the above helps, I found the most useful debugging tool for build errors was to turn on verbose output. You can turn that on in Preferences --> Android --> Build --> Build Output, then check the Console for any salient error messages.
Good luck getting your first Android app building!
Thursday, March 1, 2012
Upcoming Talks: AnDevCon III and Mobile March 3D
I'm going to be speaking at AnDevCon III! My talk is called "Don't Make Me Repeat Myself: Tips and Tricks to Avoid Code Duplication and Increase Code Reuse on Android". You can find a long description of it here.
If you register, you can use my last name ("LEW") as a $200 off coupon. This coupon should be valid all the way up till the conference. Also, if you register before March 2nd you get some pretty deep discounts.
I'm slated to give a demo version of this talk at the April AUG.MN meetup (April 3rd), if you happen to be near the Twin Cities.
I thought I'd also mention that I'm going to be briefly demoing Mobiata's apps at Mobile March's 3D event. I'll also be helping out with the Android workshop on Friday. Say hello if you happen to see me around.
If you register, you can use my last name ("LEW") as a $200 off coupon. This coupon should be valid all the way up till the conference. Also, if you register before March 2nd you get some pretty deep discounts.
I'm slated to give a demo version of this talk at the April AUG.MN meetup (April 3rd), if you happen to be near the Twin Cities.
I thought I'd also mention that I'm going to be briefly demoing Mobiata's apps at Mobile March's 3D event. I'll also be helping out with the Android workshop on Friday. Say hello if you happen to see me around.
Thursday, January 26, 2012
Another App Widget Compatibility Trick
I've written previously on the issue of preventing app widgets from appearing on particular versions of Android. This is useful, for example, when you have a Honeycomb-style widget but support pre-Honeycomb devices.
I've got a second version of this trick which I think is a bit easier now. Instead of preventing the system from seeing your AppWidgetProviderInfo, you can actually enable/disable the widget receiver itself based on configuration resource selectors.
First, setup your app widget receiver thus (important part bolded):
Then all you need to do is create a config.xml (in your /res/values/ directory) file that sets "widget_enabled":
You can then leverage the resource qualifier system to enable or disable the widget as necessary for different configurations. For example, if you wanted your widget enabled on all versions of Android except for v11 through v13, you could set it up like this:
/res/values/config.xml <-- widget_enabled=true
/res/values-v11/config.xml <-- widget_enabled=false
/res/values-v14/config.xml <-- widget_enabled=true
The main advantage this provides over my last solution is that you need only modify a bool; the other solution required you to create duplicate versions of the AppWidgetProviderInfo XML file (if you supported, say, v3 through v10 and v14+).
I've got a second version of this trick which I think is a bit easier now. Instead of preventing the system from seeing your AppWidgetProviderInfo, you can actually enable/disable the widget receiver itself based on configuration resource selectors.
First, setup your app widget receiver thus (important part bolded):
<receiver
android:enabled="@bool/widget_enabled"
android:name="com.company.appwidget.MyAppWidgetProvider" >
<intent-filter >
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/appwidget_info" />
</receiver>
Then all you need to do is create a config.xml (in your /res/values/ directory) file that sets "widget_enabled":
<resources>
<bool name="widget_enabled">true</bool>
</resources>
You can then leverage the resource qualifier system to enable or disable the widget as necessary for different configurations. For example, if you wanted your widget enabled on all versions of Android except for v11 through v13, you could set it up like this:
/res/values/config.xml <-- widget_enabled=true
/res/values-v11/config.xml <-- widget_enabled=false
/res/values-v14/config.xml <-- widget_enabled=true
The main advantage this provides over my last solution is that you need only modify a bool; the other solution required you to create duplicate versions of the AppWidgetProviderInfo XML file (if you supported, say, v3 through v10 and v14+).
Tuesday, January 24, 2012
GridLayout Child View Clipping Issues
After back-porting GridLayout to 1.5+, I finally feel comfortable using it in my apps. There's a bit of an initial learning curve, but I think that is mostly a function of un-learning the LinearLayout/RelativeLayout state of mind. I've converted a number of my own layouts to use GridLayout and found them to be much faster/easier to understand afterwards.
There was one particular issue that I ran into that is worth noting, for its solution was not immediately obvious. I was making a two-column GridLayout, where an image was on the left and text was on the right. Here's a simplified version of this layout:
The two Views would align next to each other nicely, but the TextView on the right would end up overflowing off the edge (the example below is not cropped - this is how it appears on the device):
What was happening was that the TextView would take up the entire width of the GridLayout, instead of taking up just the width of the cell (as I expected).
It turns out the solution is to set the width of the TextView to zero, then let the View fill its space dynamically using layout_gravity:
Now the problem is solved:
You need both of the highlighted attributes above; one or the other won't fix the problem. However, it will nicely solve the issue and should be kept in mind anytime you setup a GridLayout child to fill horizontally or vertically.
There was one particular issue that I ran into that is worth noting, for its solution was not immediately obvious. I was making a two-column GridLayout, where an image was on the left and text was on the right. Here's a simplified version of this layout:
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Space android:layout_width="100dp" />
<TextView android:text="@string/two_cities" />
</GridLayout>
The two Views would align next to each other nicely, but the TextView on the right would end up overflowing off the edge (the example below is not cropped - this is how it appears on the device):
What was happening was that the TextView would take up the entire width of the GridLayout, instead of taking up just the width of the cell (as I expected).
It turns out the solution is to set the width of the TextView to zero, then let the View fill its space dynamically using layout_gravity:
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Space android:layout_width="100dp" />
<TextView
android:layout_width="0dip"
android:layout_gravity="fill_horizontal"
android:text="@string/two_cities" />
</GridLayout>
Now the problem is solved:
You need both of the highlighted attributes above; one or the other won't fix the problem. However, it will nicely solve the issue and should be kept in mind anytime you setup a GridLayout child to fill horizontally or vertically.
Friday, January 13, 2012
Highlights from Android's New Design Docs
I've just finished reading through the wonderful new Android Design site Google just released. A lot of the information is stuff you should already know if you're an Android developer. However, I took notes of pages/information that I found particularly interesting (or new for ICS). Listed in order of appearance on the site:
48dp Rhythm - Like me, you may have implicitly noticed this pattern before, but it's good to see it stated so explicitly. (Same with the 8dp gap.)
Back vs. Up - Having been confused on the exact distinction for a while, this page is a breath of fresh air.
Action Bar Pattern - This entire page should be required reading for everyone. It definitely looks like the Action Bar is the future, and this is the instruction manual.
Long Touch Multiselect - Breaking news: long touch no longer activates the contextual menu. Now, it is purely for activating selection (aka multiselect). Every longtime Android developer should be aware of this change.
(Personally, I didn't even notice this change despite owning a Galaxy Nexus for a month. Perhaps that's because not even every Google app has switched to the new design yet. Or perhaps it's because long touch is just not an intuitive way to design any functionality - I've long since given up putting any core functionality into long touch. Still, it's worth noting the design shift.)
Android is not the iPhone - At least, that's what this section *should* be called. This page will be most useful for showing to your designer or boss how Android differs from iPhone and why you shouldn't just port assets and design directly from one to the other.
48dp Rhythm - Like me, you may have implicitly noticed this pattern before, but it's good to see it stated so explicitly. (Same with the 8dp gap.)
Back vs. Up - Having been confused on the exact distinction for a while, this page is a breath of fresh air.
Action Bar Pattern - This entire page should be required reading for everyone. It definitely looks like the Action Bar is the future, and this is the instruction manual.
Long Touch Multiselect - Breaking news: long touch no longer activates the contextual menu. Now, it is purely for activating selection (aka multiselect). Every longtime Android developer should be aware of this change.
(Personally, I didn't even notice this change despite owning a Galaxy Nexus for a month. Perhaps that's because not even every Google app has switched to the new design yet. Or perhaps it's because long touch is just not an intuitive way to design any functionality - I've long since given up putting any core functionality into long touch. Still, it's worth noting the design shift.)
Android is not the iPhone - At least, that's what this section *should* be called. This page will be most useful for showing to your designer or boss how Android differs from iPhone and why you shouldn't just port assets and design directly from one to the other.
Subscribe to:
Posts (Atom)


