Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

Monday, November 1, 2010

A Simple Yet Advanced Lesson in Android Programming—Changing TabWidget Tab Colors

Sometimes it’s the little problems in life that can be so challenging, but when solved are the most rewarding. As such is my experience with changing the colors on the Android TabWidget object. I spent several days and nights searching for documentation, reading the responses to questions other developers have posted, trying different things to get this simple problem solved and finally the “AHA!” moment came last night during my sleep. I woke up this Sunday morning at 6 AM with the solution on my mind. So for about an hour and half before going to church, I solved one of the greatest programming challenges I’ve faced in many years—how to change the tab colors on the Android TabWidget and keep the dividers in their proper place.

Some of you might have this figured out already, but from the great number of unanswered questions on the net, I’ll assume most haven’t. There’s so little documentation for some of these more esoteric Android features. The books I’ve read are good to get someone started with Android, some are even helpful. But I haven’t found one yet that teaches the common tasks programmers are likely to do when they’re coding.

The answer to my question was right in front of me the entire time. I found the solution in the Android SDK. I’m coding my app for Froyo or higher. The minimum SDK version for this solutions is 8. I have not tested to see if it works on the previous SDK versions. You’re on your own for that.

To illustrate what I’ve done, take a look at the two emulator screen captures below.

grey_tabs
Fig 1. Standard Grey Tabs

blue_tabs

           Fig 2. Modified Blue Tabs

The goal is to allow users to choose between a dark (Fig. 1) and light (Fig. 2) color scheme. The choice is made in a CheckBoxPreference object through the Preferences framework.

App-prefs

As soon as a user selects or deselects the Light Colors checkbox, the tab screen changes color immediately upon returning to it from Preferences.

orange_stripeIt’s really quite easy to control the tab colors. What’s not so easy is to control the orange bars that display to the left and right of a tab when it is pressed. Actually, they can be changed but it’s not recommended to do so because you have to access them through the internal Android API (com.android.internal). Doing anything through the internal API is risky. You’ll never know how the internals will change over time which can cause your application to break and security risks are inherent.

To modify the tab colors, first copy tab_indicator_v4.xml or tab_indicator.xml from android-sdk-windows\platforms\android-8\data\res\drawable to the res\drawable folder in your project. If you don’t have a res\drawable folder, create it and then copy the file from the SDK. The content of the file is:

<!-- Copyright (C) 2008 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
  
          http://www.apache.org/licenses/LICENSE-2.0
  
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
     implied. See the License for the specific language governing
     permissions and limitations under the License.
-->

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Non focused states -->
    <item android:state_focused="false" android:state_selected="false"
        android:state_pressed="false"
        android:drawable="@drawable/tab_unselected_v4" />
    <item android:state_focused="false" android:state_selected="true"
        android:state_pressed="false"
        android:drawable="@drawable/tab_selected_v4" />

    <!-- Focused states -->
    <item android:state_focused="true" android:state_selected="false"
        android:state_pressed="false"
        android:drawable="@drawable/tab_focus" />
    <item android:state_focused="true" android:state_selected="true"
        android:state_pressed="false"
        android:drawable="@drawable/tab_focus" />

    <!-- Pressed -->
    <item android:state_pressed="true"
        android:drawable="@drawable/tab_press" />
</selector>

The @drawables in this file control the appearance of the tabs in their various states, i.e. pressed, focused, selected, etc. These drawables are .png graphics located in your project’s drawables-hdpi directory. You can get the graphics referenced in this file from the drawables-hdpi directory for the platform of your choice in the Android SDK. You assign this file as the background resource for your tabwidget.

I created two versions of this .XML file. The first is for the dark theme, the other for the light theme. The only difference is the name of the @drawables graphics I’m using in each. To make the blue selected and unselected .png graphics I made copies of tab_selected_v4.9.png and tab_unselected_v4.9.png from the SDK. Then I used the color replacement tool in Photoshop to create the new images.

The following Java example is a custom method I wrote for my app’s tab activity to set the background resource to either file based on the user preference IsLightColors.

protected void setTabColors() {

   /** * Before we do anything, determine saved value of
         IsLightColors */

    MyApp app = (MyApp) this.getApplication();
   
IsLightColors = app.RetrieveBoolean(getString
       (R.string.LightColorsKey));

    /** set the color scheme based on IsLightColors user pref
    */
    View myLayout = findViewById(R.id.main_layout);
    if (IsLightColors) {
       myLayout.setBackgroundColor(Color.WHITE);

        for (int i = 0; i < tabHost.getTabWidget()
           .getChildCount(); i++) {
           tabHost.getTabWidget().getChildAt(i)
     .setBackgroundResource(R.drawable.tab_indicator_v4_light);
        }
    } else {
       myLayout.setBackgroundColor(Color.BLACK);

       for (int i = 0; i < tabHost.getTabWidget()
           .getChildCount(); i++) {
           tabHost.getTabWidget().getChildAt(i)
     .setBackgroundResource(R.drawable.tab_indicator_v4);
       }

   }
}

This code snippet references app.RetrieveBoolean. You won’t find this method in Android. This is another custom method I wrote for an app-level extension library. Using this method, we obtain the value of IsLightColors from the Preferences framework and the if statement does the rest!

Now before you point out any coding inefficiencies like the duplicate code blocks you see in the if-else construct, please note that I’m all for writing functional code in the smallest chucks possible. Code efficiency must be a priority especially when writing for small, portable, memory challenged devices. setTabColors() refactored for efficiency looks like this:

    protected void setTabColors() {
       

/* * Before we do anything, determine saved value of IsLightColors */
        MyApp app = (MyApp) this.getApplication();
        IsLightColors = app.RetrieveBoolean(getString(R.string.LightColorsKey));
       
  // set the color scheme based on IsLightColors user prefs
        int tab_indicator = IsLightColors ? R.drawable.tab_indicator_v4_light : R.drawable.tab_indicator_v4;
        int layoutColor = IsLightColors ? Color.WHITE : Color.BLACK;

        View myLayout = findViewById(R.id.main_layout);
        myLayout.setBackgroundColor(layoutColor);
       
// set the background resource for each
        for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
                tabHost.getTabWidget().getChildAt(i).setBackgroundResource(tab_indicator);
        }       

    }

}

Notice the if statement is gone and there is no duplicate code. Writing more efficiently means greater speed in execution. I certainly hope this has shed some light on the tab color issue and helped you in your quest to customize your tabs.

Wednesday, October 13, 2010

Motorola Acknowledges Droid X Froyo 2.2 Bugs—Fixes Coming

Matt, the Droid X forums manager inn the Motorola support forums, posted this blog article yesterday acknowledging some of the issues with the Droid X Froyo 2.2 release:

If you have already upgraded to 2.2 for Droid X, you have found some new capabilities. Unfortunately, some owners also found new issues.  Here are some of the known issues raised by forums members, with some information about each. It is not intended to be a complete list at this time -- there are many more fixes and improvements in the works. I’ll update this list as information becomes available.

  • Stuck on Moto logo after reboot – this was tough on a few owners. Very sorry about that. A fix has been developed for this and should eliminate the problem. It will be distributed in a future software release. If you are still experiencing this issue, click here.
  • Random rebooting – while there always seem to be new conditions that can cause an electronic device to panic, we do have improvements coming that address and eliminate identified panic states. They will be distributed in a future software release.
  • Wi-Fi connection and stability – improvements in Wi-Fi have been developed, to address several problem areas. They will be distributed in a future software release.
  • Battery Manager “force close” errors – under some circumstances, pressing the battery icon under Menu > Settings > Battery Manager results in a forced close error. A fix has been developed for this and should eliminate the problem. It will be distributed in a future software release.
  • Media won’t play – includes “sorry the player does not support this type of audio file," custom ringtone stop working, video won’t play, etc., until after a reboot. We believe we have identified the cause of these errors. A fix has been developed for this and should eliminate the problem. It will be distributed in a future software release.
  • Music files cutting off the final four seconds or so – a solution has been developed. It will be distributed in a future software release.

At this time I don't have information about when the next software update will be available -- when I have it, I'll share it here.

https://supportforums.motorola.com/thread/38876

Monday, October 11, 2010

Setting Up an Android Development Environment

My HP DV8T laptop is now setup as an Android application development environment. It was very easy to do so and everything worked the first time. I was able to create, test and debug the infamous “Hello World" app within 5 minutes of having completed the environment. The instructions I am providing here are for the Windows platform only. If you want to program in Linux or on a MAC, please visit the Android Developer Site for those platforms’ details.

To get going, you only need four things, two of which are required and two are optional:

  1. Java Development Kit (JDK) version 5 or 6
  2. Android SDK
  3. Optional: Eclipse Version 3.4 or 3.5
  4. Optional: Android Development Tools (ADT) Plugin

If you are new to programming, the term “SDK” means “Software Development Kit.” SDKs are sometimes called “devkits.” Typically, a SDK is a set of tools that allows for the creation of an application for a specific software package, software framework, hardware platform, computer system, video game console, operating system or similar platform.

Java JDK

The Java Development Kit is available at Oracle's Java Download site. Simply download either the 32-bit or 64-bit version of the JDK depending on your OS version and run the program to install.

Eclipse

Eclipse is a very popular and free integrated development environment (IDE) available from Eclipse.org. An IDE provides comprehensive facilities to computer programmers for software development. An IDE normally consists of: a source code editor, a compiler and/or an interpreter, build automation tools and a debugger. For developing Android applications, it’s recommended that you install one of these packages:

  • Eclipse IDE for Java EE Developers
  • Eclipse IDE for Java Developers
  • Eclipse for RCP/Plug-in Developers
  • Eclipse Classic (versions 3.5.1 and higher)

There’s one BIG caveat to installing Eclipse. The Android Development Tools Plugin has known incompatibilities with the current version of Eclipse (3.6). If you are installing a fresh environment, it is recommended that you install version 3.5.x. I decided to install the 3.5.2 classic version and it was a painfully slow download. The package is a 168mb .zip file that took two days to download. The download kept timing out and I had to restart it many, many times. I’m very grateful that each time I restarted the download, it picked up again from where it had previously stalled. Unzip the Eclipse .zip file to the location of your choice and create a shortcut to the Eclipse executable and you’re ready to go. There is no Eclipse installer to run.

Android Development Kit

The Android Development Kit (ADK) is another .zip file like Eclipse. Once it’s downloaded, unzip the file to the location of your choice. Again, like Eclipse, there is no windows installer to run. It’s important to note that what you have just downloaded is the ADK starter package only. You haven’t downloaded any of the real ADK SDKs yet. To download the actual SDK and Google application programming interfaces (APIs), run the SDK Manager program located in the directory in which you unzipped the ADK starter package.

When you run the SDK Manager, you’ll be presented with a list of available SDK and API packages. I installed the Android 2.1 and 2.2 SDKs, samples for the two SDKs, APIs 7 and 8, documentation for API 8, USB Driver package and Market Licensing package. Once selected for download, the items download and install automatically. Google has done a great job making the install as easy as possible for developers.

After the SDKs are downloaded and installed, create at least one virtual device with the SDK Manager. The virtual device is a SDK platform specific emulator you can use later for testing your applications.

Android Development Tools Plugin

The Android Development Tools Plugin is installed from within Eclipse itself. To install the ADT, follow these directions from the Android Developer web site:

  1. Start Eclipse, then select Help > Install New Software.
  2. In the Available Software dialog, click Add....
  3. In the Add Site dialog that appears, enter a name for the remote site (for example, "Android Plugin") in the "Name" field.

    In the "Location" field, enter this URL:

    https://dl-ssl.google.com/android/eclipse/

    Note: If you have trouble acquiring the plugin, you can try using "http" in the URL, instead of "https" (https is preferred for security reasons).

    Click OK.

  4. Back in the Available Software view, you should now see "Developer Tools" added to the list. Select the checkbox next to Developer Tools, which will automatically select the nested tools Android DDMS and Android Development Tools. Click Next.
  5. In the resulting Install Details dialog, the Android DDMS and Android Development Tools features are listed. Click Next to read and accept the license agreement and install any dependencies, then click Finish.
  6. Restart Eclipse.

Hang in there, we’re almost done. There’s one step left and you’ll be on your way to developing your first Android application. Now that the ADT is installed, it needs to be configured to work with the Android SDK. To configure the ADT, you must point it to the Android SDK directory. From within Eclipse:

  1. Select Window > Preferences... to open the Preferences panel
  2. Select Android from the left panel.
  3. For the SDK Location in the main panel, click Browse... and locate your downloaded SDK directory.
  4. Click Apply, then OK.

Android Market Developer Account

Once you start writing your own Android applications, you might just be the one to make a fortune with “the killer app” that everyone else dreams of writing. To sell on the Android Market, you must have an Android Market Developer account. Google charges $25.00 USD to open an Android Market account. They also make it very easy to accept payments through the Google checkout system once you have an Android Market account by offering you to open a Google checkout merchant account. As with any merchant account, Google charges a transaction fee on each of your sales. The normal transaction fees are based on a sliding scale determined by the amount of your monthly sales. For example, if you sell less than $1,000 per month, you pay 2.9% + $.30 for each sale. But for anything sold through the Android Market, the fee structure is vastly different.

As of the time of this writing, the transaction fee for anything sold through the Android Market is 30%. Yes, that’s right! Google charges a whopping 30% fee on anything you sell through the Android Market and of course, you are responsible for collecting and paying any applicable sales taxes. If only I had the foresight to buy Google stock back in the day!

Thursday, October 7, 2010

Reinventing Yourself as an Android App Developer

I’ve spent a large portion of my professional life as a software developer. I’ve written applications for video stores, doctors, lawyers, insurance companies, banks, and some of the world’s largest corporate entities both as a consultant and full-time employee. For the last eight years, I’ve worked purely in corporate management, but to keep my development skills somewhat honed, I’ve taught myself .NET, specifically C#. My personal web sites are all C# .NET. Over the years, I’ve written applications in C, C++, xBase, Smalltalk, Turbo Pascal, Java, Perl and PHP, just to name a few of the languages in which I’m conversant. I never went to school to learn how to be a programmer, yet it’s been a great source of my success, satisfaction and income over the years.

The first language I ever learned was basic. I had been given a Timex Sinclair 1000 as a Christmas present. In 1982, computers were vastly different than they are today. My Droid X has more processing power than my old Timex did. It hooked up to a TV as a monitor and it stored data on an audio cassette. Primitive as it was, for me it was the beginning of a life-long learning experience. Using that computer, I learned how to write software and I started getting my software review articles published in a variety of magazines. It was definitely a launching pad for my IT career.

I’ve never been afraid to try new things and learning new languages generally comes very easily to me. After all, how many different ways are their to write loops and branches. And of course, there’s always pointers and garbage collection to contend with! But object-oriented is object-oriented. I believe that if you know the basics, it’s a rather trivial matter to apply them to different languages. But rest assured, I  didn’t always have the confidence in my abilities as I have today. If anyone should receive credit for building the confidence I have as a developer, it is Lynn Lehman.

Lynn was a manager I reported to for a time when I was a contractor at JP Morgan Bank on Wall Street. I didn’t care for Lynn very much. I think I rubbed him the wrong way and it showed. I thought he was arrogant, condescending and held a superior attitude over others. (These are exactly the same adjectives people used to describe me in my first corporate 360 evaluation after I became a manager at Warner-Lambert.)

Lynn called me into his office one day and asked me to write an application in Lotus Notes. At that point I had never even seen Lotus Notes, let alone know its programming language well enough to write an application. Lynn wanted an issues tracking database. The foreign exchange currency trading system we just spent 2.5 years developing had rolled into production. Now the development team was transitioning into maintenance mode and Lynn wanted an application to track issues and bugs. He wanted it done in Lotus Notes.

My initial reaction was to protest and say no because I didn’t know Lotus Notes. Lynn just looked at me and very calmly asked me, “Are you a professional programmer or not?” After pausing to recover from this lightening strike, I said, “Yes I am.” Then he said, “So write me a program in Lotus Notes. I want it complete in 6 weeks.” I delivered the fully functioning and tested application in 4 weeks.

A May 2004 article in USA Today called Madonna “The Mother of Reinvention.” This was because she was travelling the world at that time on her “Reinvention Tour.” With today’s high unemployment and significant competition for jobs, many people today are  reinventing themselves, perhaps transitioning into completely different careers than they did before.

So far this year, I’ve written my first book and became a registered facilitator for the Lead Like Jesus servant leadership encounter workshop. As I continue to seek gainful full-time employment, I’ve decided to reinvent my developer skills somewhat and perhaps create an income stream in the process. I’m going to reinvent myself as an Android app developer in addition to all the other irons I have in the fire right now.

How am I going to do it? Well, I’m going to take baby steps at first. It’s been a while since I’ve written any production-level code. Finding my next job and continuing my networking activities are still priority #1. The first step though is setting up one of my computers as a development environment. I’m going to use my HP DV8T laptop for this. In my next post, I’ll share how to setup the development environment.

Tuesday, October 5, 2010

Top 20 Favorite Android Applications

Never have I been more pleased with a cell phone than I am with my Droid X. I don’t know if it’s the sophistication of the hardware, the capabilities of the Android operating system or the enormous amount of apps that are available in the market place. But whatever “IT” is, I am enthralled.

I’ve spent more time in the past two weeks browsing forums, reading reviews, and trying out specific apps to make the phone work the way I want it to work. I’ve found many lists for what certain writers consider to be the “best” or “essential” or their “favorite” droid apps. I was pleased to see that many people agree with the choices I’ve made independently of these lists, but then again, there are some apps that I love that nobody else seems to know much about. And I know, I’m only beginning to scratch the surface. So let me share with you what I subjectively consider to be favorite android applications. All of them are either completely free or have free versions available that can be upgraded to “Pro” versions.

  1. Astro File Manager by Metago: Rated by many websites as the best file manager available for Android, Astro allows you to manage files on your SD Card. You can execute functions such as copy, delete, move or rename; send files as attachments or manage running applications. Modules are available to Bluetooth OBEX FTP and SMB (Windows) networking features.
  2. Compass by Catch.com: Displays a compass, location and geo-tagged notes.
  3. Congress by Sunlight Foundation: Everything you ever wanted to know about Congress. Find your representatives using your location, get their contact information, see how they vote, follow bills through the process and read the newest laws.
  4. Dial Zero by Next Mobile Web: Tired of wading through endless interactive voice prompts when trying to reach a real person in customer service? Not anymore!. Dial Zero provides direct customer service numbers to over 600 companies. 
  5. DroidLight: A flashlight app from Motorola that allows you to turn the camera’s LED flash on and off like a flashlight. The Droid X’s twin LEDs are very bright. The flashlight app helps you to easily find the keyhole in the dark.
  6. Google Goggles by Google Inc.: This is an amazing app that you need to use to believe! Take a picture of an object with your cell phone, Goggles attempts to recognize the object and return relevant search results.
  7. Google Shopper by Google Inc.: Shopper uses the camera to recognize cover art, barcodes and can perform voice and text searches to find local and online prices, reviews, specs and more.
  8. Google Sky Map by Google Inc.: Turns your Android based phone into a mobile planetarium. Hold the phone up to the sky and it uses your location to display the constellations you are seeing.
  9. Google Translate by Google Inc.: Instantly translate text between 50 languages. Can use speech to text for recording and text to speech for playback.
  10. Handcent SMS by handcent_admin: Full featured SMS/MMS replacement app for Android phones. Overcomes the weaknesses of the built-in app. Includes group sending options.
  11. Key Ring by Mobestream Media: Tired of all the little membership reward cards cluttering your key ring? Scan them into this app and make room in your pocket. Display the barcode on your phone at checkout and have the clerk scan the phone instead. I’m still on the fence about this one. I’ve used this at two different stores and the scanner was unable to read the barcode on the phone. presumably due to the reflective nature of the phone.
  12. Kindle Book Reader: Free app from Amazon.com that is preloaded on the Droid X. I was pleasantly surprised to see there are over 3,000 free books available for the Kindle Reade, most of them classics and all either in the public domain or offered free by their authors.
  13. KJV BibleReader by Olive Tree: Nary a day goes by where I don’t do at least some devotional reading. The Olive Tree KJV BibleReader is a free download and includes the King James Version. Makes searching for specific passages easy. Tap “Library” to browse the store and download many free books and study guides.
  14. Lookout Mobile Security by Lookout, Inc.: Provides antivirus, system backup and phone finder features for free. The phone finder is really cool. If the phone is lost of stolen, you can locate it on the map. If you’ve misplaced the phone around the house as I often do, you can send a blaring siren signal to the phone. Siren works even if the phone is silenced.
  15. Mileage by Evan Charlton: A very simple app, Mileage lets you track your vehicle’s fuel consumption history and calculates lots of useful stats.
  16. Note Everything by SoftXPerience: This is the most comprehensive note taking application I’ve found for Android. Create Textnotes, Paintnotes, Voicenotes, Photonotes, Checklists, Durable Checklists (ToDo lists), Gallerynotes, Notes from barcodes, Reminders or Notes from Google docs. Stick notes to the status bar and automatically back them up on the SD Card.  Great support and frequent updates.
  17. Ringdroid by Ringdroid Team: Creates ringtones from your own music tracks or record a new one directly from the phone.
  18. Scanner Radio by Gordon Edwards: As a former professional paramedic, I still enjoy listening to emergency calls from time to time. Scanner Radio allows us to listen to live emergency audio from over 2,300 police and fire scanners, railroad communications and weather radio broadcasts from around the world.
  19. Shop Savvy by Big in Japan, Inc.: If there’s only one shopping application for you to get, this is the one. Shop Savvy uses your location to comparison shop products in your area or online. Supports QR Codes.
  20. TuneWiki Social Media Player by TuneWiki: Shows subtitled lyrics as you listen to music, watch music videos, or stream songs through SHOUTcast radio. Integrates with Facebook and Twitter.