Ruby, Rails, And Friends

For the last 6 months I’ve been slowly teaching myself Ruby on Rails. It’s been a lot of fun and I’ve loved most every minute of it. My last run at web development was several years ago before technologies like Heroku were common. I spent some time trying to learn Django but did not find the ecosystem quite as mature as I would have liked. I found myself stuck playing sysadmin on a webserver, which is a role I am neither interested in or great at. So I hung up web development, experimented with mobile went back to desktop application development.

Four years later, enter Ruby on Rails. I’m having a blast. The tools are great. The community is wonderful. And after spending every day for two years with my nose buried in Visual Studio I am thrilled to be back to vim. It is _Bliss_.

I’m active on GitHub and attend several regular meetings and extra events with the Ruby community. I’ve made tons of new friends and enjoying all of it. I’ve hardly played a video game in months and I can hardly believe it. I’ve got motivation to work a full day and then another three or four every night. It’s all fun.

If you feel like you’re missing something in your life as a developer try to find a local group. It has made all of the difference.

RPS contest

The other week I came across a neat programming challenge called The RPS(Rock Paper Scissors) Programming Competition. The goal is to write a Python program that plays RPS against other programs. Each match is a best of 1,000.

This challenge caught my interest with its unique combination of ease and depth. While my best submission has dropped to a roughly 60% win rate there are some truely clever programs submitted. I am certain I can improve greatly and develop a submission over the coming weeks that is able to achieve a 70% win rate.

I would encourage anyone who enjoys programming or problem solving to give it a go.

Why I Love Android Development

Android development strikes a sweet spot for me, as a developer seeking to be a contributing member in the software community.

I have taken a few shots at web development and it just doesn’t feel right. While it is such a visual and rewarding experience. I just can’t shake the feeling of it being the most phenomenal kludge.

It is easy to distribute and consume in an almost completely platform independent environment. I love being able to send a someone a link and say, “Hey, check this out!” and have them be greeted by a slick web app.

But despite all of this it still feels wrong.

Android offers you a much more consistent development platform while simultaneously keepingĀ  much of the ease of distribution alive.

I like how Android development feels like a merger between web accessibility and desktop consistency.

I do realize that Android has its own host of complexities such as the numerous possible devices, API versions, and the challenges of the application lifecycle.

It won’t say that it is perfect, but I am comfortable saying that it feels very right.

Android Soft Keyboard, IME, For Dialogs

It seems like such a simple thing, you would like to show the Soft Keyboard automatically for a Dialog. You can easily find a number of ways to do this for an Activity. You can also find one often repeated, but inadequate, method being proliferated for a Dialog

InputMethodManager imm =
(InputMethodManager) getSystemServer(INPUT_METHOD_SERVICE);
imm.toggleSoftInput(imm.SHOW_FORCED, imm.HIDE_NOT_ALWAYS);

There are, however, several problems with this method. It does not…

  • respect the user’s phone and presence of a physical keyboard
  • close automatically when the dialog closes
  • close automatically if the user were to leave the activity or application completely

There is however, a solution if you are targeting at least API Level 3 (Android 1.5). In your `onPrepareDialog()`, or wherever you are displaying your dialog do the following:

dialog.getWindow()
   .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

This will have the same result on a Dialog as setting android:windowSoftInputMode="stateVisible" for an activity in your `AndroidManifest.xml`

Custom Android RadioButton

I was browsing StackOverflow and came across a question about making custom RadioButtons I figured I could answer so I decided to take the plunge.

So here is how to implement a custom styled RadioButton, you can find the source here.

To do so, you need to take the following steps:

Create the drawable resources for your custom RadioButton. You should have at least 4 icons:

Pressed Checked
True True
True False
False True
False False

Place your images in res/drawable or if if you make version for each screen density in their corresponding res/drawable-ldpi, res/drawable-mdpi, and res/drawable-hdpi folders.

Then create a selector type XML file in res/drawable. Here is my res/drawable/button_radio.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_checked="true" android:state_pressed="false"
      android:drawable="@drawable/radio_on"/>
  <item android:state_checked="false" android:state_pressed="false"
      android:drawable="@drawable/radio_off"/>
  <item android:state_checked="true" android:state_pressed="true"
      android:drawable="@drawable/radio_on_pressed"/>
  <item android:state_checked="false" android:state_pressed="true"
      android:drawable="@drawable/radio_off_pressed"/>
</selector>

Then set-up your RadioGroup like so:

<RadioGroup android:layout_width="fill_parent"
   android:layout_height="50dp"
   android:orientation="horizontal"
   android:checkedButton="@+id/first">
   <RadioButton android:id="@+id/first"
      android:width="50dp"
      android:height="50dp"
      android:button="@drawable/button_radio"/>
   <RadioButton android:id="@+id/second"
      android:width="50dp"
      android:height="50dp"
      android:button="@drawable/button_radio"/>
   <RadioButton android:id="@+id/third"
      android:width="50dp"
      android:height="50dp"
      android:button="@drawable/button_radio"/>
   <RadioButton android:id="@+id/fourth"
      android:width="50dp"
      android:height="50dp"
      android:button="@drawable/button_radio"/>
</RadioGroup>

I have specified dimension of 50dp as the dimension of my drawables are 50px x 50px. Also notice I am setting android:button and not android:background.

Hopefully this can serve as a nice starting point for anyone looking to create some new and interesting effects with simple RadioButtons.

Android TextView With Custom Link Text

This is just going to be a quick how-to on creating a TextView with custom URL text.

To do this, you need to create a Spannable text object by using Html.fromHtml and then setting the MovementMethod of the TextView to a LinkMovementMethod. Here is an example using a dialog.

dialog = new Dialog(this);dialog.setContentView(R.layout.about);
dialog.setTitle(R.string.about_score_it);
TextView website = (TextView)dialog.findViewById(R.id.about_website);

String realURL = "http://blog.devminded.com/projects/score-it";
String visibleURL = "http://blog.devminded.com";

//The following builds the spannable item and will cause the text to display as a link
website.setText(Html.fromHtml("<a href=\" + realURL + "\">" + visibleURL + "</a>"));

//The following makes it clickable
website.setMovementMethod(LinkMovementMethod.getInstance());

Or with resources:

dialog = new Dialog(this);
dialog.setContentView(R.layout.about);
dialog.setTitle(R.string.about_score_it);
TextView website = (TextView)dialog.findViewById(R.id.about_website);         

website.setText(Html.fromHtml("<a href=\"" + mRes.getString(R.string.about_score_it_website_url) + "\">" + mRes.getString(R.string.about_score_it_website_text) + "</a>"));

website.setMovementMethod(LinkMovementMethod.getInstance());

To see the full context of this example please check out ScoreIt.java

Android SQLite Database Management

Just as I was trying to wrap up Score It! I noticed my Logcat window was getting flooded with error messages. Somehow during all my debugging and development I didn’t notice the pages of errors being thrown by SQLite.

java.lang.IllegalStateException ... SQLiteDatabase created and never closed

Now these errors didn’t appear to have any adverse affects on my application but I certainly did not want to release an app that I knew was spewing errors. I wrestled with this for an evening searching and trying everything I could think of.

Some people suggested opening and closing the database around all accesses. Others suggested littering all of the lifecycle overrides with open and close statements. I found the former unreasonable and the latter inadequate. I needed to keep my database connections open as much as possible because I was working with ListView and ListActivity objects.

I managed to reduce the frequency of the errors but it was still happening consistently if I followed specific steps but I decided to throw in the towel for the time being.

The next day I decided to revisit the issue and make sure I had a better understanding of the problem. I stepped through my app, using a ridiculous number of breakpoints. It soon became clear that it was not a specific line of code that was causing the problem. This error was being generated by the database object when the garbage collector was hitting it.

I experimented a bit further and came up with a solution that seemed to eliminate all of my SQLite database errors.

In the Activities that maintained a database connection I put a close() statement in the Activity.OnDestroy() override:

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mDbHelper.close();
	}

In my database helper class, modeled after Notepad, I changed the open function from:

    public ScoreDbAdapter open() throws SQLException {
		mDbHelper = new DatabaseHelper(mCtx);
		mDb = mDbHelper.getWritableDatabase();

        return this;
    }

To the following:

    public ScoreDbAdapter open() throws SQLException {
    	if (mDbHelper == null) {
    		mDbHelper = new DatabaseHelper(mCtx);
    	}
		mDb = mDbHelper.getWritableDatabase();

        return this;
    }

This cleared up all the errors.

Score It! Released!

Finally!

My very first Android application, Score It!, has been released. It’s been an exciting experience, and I’m glad to finally have something I’ve made “out there.” It is a very liberating feeling.

It’s easy to be self conscious about the code you write, but I don’t want to do that any longer. By releasing an application and releasing the source (Apache 2.0 License) I hope to grow, become a better developer, and help others.

Going forward, I plan to revisit many of the challenges I encountered in making Score It! and document how I solved them. I hope my exploratory programming will help someone else as well as me.

Score It! QR Barcode

Android users click

Android LogCat

I sure wish I had found Android LogCat sooner. Even one day without it was too many. I spent three. Since becoming aware of it my Android development experience has been so much better.

Those first days working on Android were fun and exciting but left me confused by the complete lack of feedback when an application crashed. I was debugging my crashes down to the line they were dying on and still not getting any useful information.

Then I found out how to use LogCat. But not before I got burned a few times by subtle but critical mistakes.

To get the LogCat view simply go to the menu bar and select Window> Show View> Other. You will be presented with the following window, just select LogCat.

Adding LogCat to the current Eclipse Perspective

Adding LogCat

LogCat will now be added to your list of views in your current perspective. When the LogCat tab or window is active you are then presented with several more icons that allow you to filter on the log message level and create additional filters.

LogCat filter options

LogCat with only error level messages

Now all stack traces and other logging messages will be dumped to LogCat when a debug enabled Android device (virtual or physical) is attached.

You can add additional debug or logging messages of your own by using android.util.Log.

Testing some java

As my first post, to test the layout and some plugins, I have decided to share a little Java class that converts a String input to an int. While it is not perfect, it seems to work well enough under the constraint of not using library functions to do the conversion.

When I wrote it I decided to just throw decimal point entry to the wayside. However, looking back at it I could have allowed it and either floored the value or only permitted whole number values.

Overall I think this implementation handles the problem statement without over-complicating matters.

public class StringToInt {

	public static int strToInt(String input) {
		
		int number = 0;
		int negFlag = 1;
		int count = 0;
		for (char s : input.toCharArray()) {
			if (s == '-') {
				if (count > 0) {
					throw new NumberFormatException();
				}
				negFlag = -1;
				continue;
			}
			if (s < '0' || s > '9') {
				throw new NumberFormatException();
			}
			number *= 10;
			
			number += (s - '0');
			
		}
		return number * negFlag;
	}
}