Archive for the ‘ Programming ’ Category

Android EditText setFocusable(true) does not work if you remove focus

I came across this weird issue where the EditText view, once focus was removed, would not allow you to type even if you set it to focusable again. I was basically doing this:

editTextField.setFocusable(someCondition);

The problem was though that the view would get focus again, but you couldn’t type anything. I googled around for a bit and noticed this was an issue that had been previously reported, but hadn’t been fixed yet. There is a way around it however, you just have to do:

if (someCondition)
   editTextField.setFocusable(false);
else
   editTextField.setFocusableInTouchMode(true);

Setting it true in setFocusableInTouchMode() seems to do the trick, at least until it is fixed.

CAA – Canadian Automobile Association application release

I meant to post an update about this, but for some reason it completely slipped my mind. On Nov. 17, the CAA application (my very first mobile application I got to work on!) was approved by CAA and all the app stores, so it is now available for public download!

You can get the different platform versions:

I hope you get to test it out if you get a chance! I think trying to write about all the different things I learned during this project would be at least a 20 page essay, so I’ll try to highlight the key points:

  • It is extremely important to anticipate and think about areas of change in your code. Code will have to be written to be as easily modifiable as possible. This means low coupling, high cohesion, minimal hard coding, using OO paradigms (Android and BlackBerry use Java, iPhone uses Objective-C), and being ready for change. You will get changes to the requirements, it is possible some things may not be possible, and although these requirements should all be determined at the beginning of the project, that is a perfect world situation that I have yet to experience.
  • Meetings are good, but too many meetings, or overly long meetings are terrible. Having a quick meeting to update and sync up with the status of the project and any issues on a daily or weekly basis is great. However, if these meetings drag on too long, then it’s pretty much a waste of time.
  • Design patterns are awesome. Use them. People have been developing for a long time, so use the plans they have laid out!
  • Testing is incredibly important. And there are many, many kinds of testing. They are all important. It’s better to catch all your bugs before things go into production because user feedback about how to duplicate a bug is not often helpful. Try to set it up so that if your application crashes it can email you the crash log, which is infinitely more useful than a user description.
  • User experience can make or break an application. I can write an extremely difficult application which took years to develop and can do everything from tell you the time to drive your car, but if you can’t figure out how to use it, it’s worthless. Applications that are simple to program, but easy to use, are what make it to the top of the app store lists. Make sure you get a designer to help you out with it, and do some user experience testing as well.
  • Meet all your deadlines, but don’t freak out about your deadlines. In the beginning I would worry, fret, panic, and have multiple heart attacks on delivery days. All very useless. Work on it consistently and make sure you do all your testing at least a day before the delivery date. When you change how something work 2 minutes before a release is supposed to go out, you should go through all your tests again. Just because it works for the one case doesn’t mean it works for everything!
  • BugZilla (or a bug tracking software) is only useful if you know how to use it. We were using BugZilla to keep track of all of our incoming bugs, closed bugs, and just generally keeping track of things through it, but I could not for the life of me figure out how to use it. I had to go through an incredibly painful process where I set up email notification for every bug opened, and then I would save all those emails, and when the time came, open up every single email to try to figure out which bugs were open, closed, in progress, or not bugs anymore. (I really wish they would upgrade their system … it’s still so hard to use!). Eventually I kind of figured out how to use it for my project and my bugs, and it became easier.
  • Whether you choose to use Git, SVN, Mercurial, make sure you fully understand how to use it. There are benefits and drawbacks to each, make sure you know how to use your chosen repository system’s features.

I think the last two points can essentially be summarized to: know how to use the tools you’re developing with. I think that’s a long enough list, however. I hope that’s useful to someone if they ever come across it!

And if you can, download the app and tell me how it goes for you! Let me know if I can make it better for you, and how :).

Easy Redundancy Fix

A really common mistake (or redundancy issue) I see often is the following:

if (someCondition) {
     //some code
     return something;
} else {
     return somethingElse;
}

A return statement steps out of the method and returns to the point where it originated. Thus, if the first condition is met, it will exit the method and not execute any other statement. Then you simply have to do:

if (condition) {
    //execute some code
    return something;
}
return somethingElse;

To be even better, if you are doing something like:

if (cond) {
   return true;
} else {
   return false;
}

Notice that if the condition is true, you return true. If it is false, you return false. You may as well return the conditional statement! So:

return(cond);

It’s really simple and very obvious, but it’s just something I see quite often.

And one I missed but pointed out by Gooble in the comments:

(booleanExpression ? trueResult : elseResult)

An if/else kind of statement, but as a one line operation! Also useful when you’re just assigning variables a value based on some condition, or returning something.

Hope that was helpful!

Commit Early, Commit Often

One of the most important lessons I’ve probably learned over this past week is the mantra that should be drilled into every programmer’s head and then explained:

Commit Early, Commit Often

Even though I’ve been told and heard in the past numerous times that to commit early and commit often is a good thing, I didn’t do a very good job of it in practice. For some reason, I didn’t want to commit anything until I had completed a large portion of code, or a new feature, or fixed not one or two, but many bugs. I basically wanted to build a program / project with as few commits as possible.

I talk about this with respect to version control systems, I think they’re incredibly useful and once you start using them, you’ll never go back to life without them.

Reasons why I thought this was good: 

  • If I commit now, it might cause conflicts with the other person working on this as well, which will be problematic. I don’t want to screw up my code by updating, so I’ll just finish up a lot and make it work.

BAD: This actually doesn’t make a lot of sense. I wasn’t even able to convince myself of this. There will be conflicts if more than one person is working on the same function in the code or same area. There will be MORE if you commit after a long period of time. If you commit early and commit often, small conflicts will be easy to change and fix as opposed to a huge one.

  • I don’t want to look like a bad programmer by submitting things that might not be complete or really neat … I’ll just fix it up later and then commit.

BAD: This is terrible! The only way you can improve is by practicing, and by receiving critique. If you let no one look at your code for fear of judgement and being thought of as inferior, how will you improve? Secondly, just try to learn as much as possible!

  • I will commit after I have completed feature x or y, or after I have fixed bugs x, y, z, and q.

BAD: Commit early and commit often! This is in direct violation of that rule! If you wait until you have a big feature or a lot of bugs fixed, it can cause problems! You might lose your data, your files can get corrupted (all worst case scenario things of course, but Murphy’s always waiting to strike!) and then you’ll lose everything you worked for. Commit early and commit often.

  • I don’t want to break the build.

GOOD/BAD: It’s excellent to not want to break the build, it’s not good to refuse to commit for large periods of time. Better to test your code out (I’ve heard in Microsoft they test on three different machines with a variety of tests before they add the code to the build).

Reasons that you should always, always always commit early and commit often:

  • Your code is not you. Receive feedback, critiques, improve code, do not make same mistake again. Life’s all about that, isn’t it?
  • If someone catches a mistake you’re making early on (or even you do), then it’s super easy to rectify in the beginning, as opposed to later in the game. Then it gets 10x harder. I believe there’s a law for this that goes something like:

The amount of effort/difficulty to fix a bug that is found increases 10x for each stage that it is missed in (the stages being requirements, design, implementation, verification, production, and then maintenance).

  • If something corrupts, you have a revision that was working pretty close to the one you have right now!
  • If you haven’t committed and someone else commits code and then your code breaks after they commit, you can’t really argue their code is the reason for this. It can possibly  be the reason, and it is also possible that there was something in your code that is wrong.
  • If you make a really stupid delete file or overwrite file mistake, retrieving it is not difficult at all!

That’s all I can think of at the moment, but I hope I’ve convinced or argued enough to help anyone reading this to remember to COMMIT EARLY, COMMIT OFTEN!  I learned this the hard way, hopefully my example will be enough to save others!

Android: layout_gravity vs. gravity & wrap_content vs. fill_parent

When creating the user interface in Android, you can choose to use the interface builder that is provided (for Eclipse) or you can edit the XML files. I usually prefer editing the XML files because dragging around the different elements on the canvas and scrolling through the properties of each object gets tedious. If you edit the XML file you can also pretty much copy paste in elements of code that are repeated from screen to screen.

In the beginning, I often made a mistake regarding two major topics: content fill, and alignment. For content fill there are two important properties you need to know: wrap_content and fill_parent. For alignment you need to know the difference between the layout_gravity and gravity attributes.

layout_gravity vs. gravity

layout_gravity sets the gravity (alignment) of the View or Layout inside its parent. If you have a text view inside a linear layout, then setting the layout_gravity of the text view will alter its alignment in the layout. gravity sets the alignment of the content of the view or layout it is applied on. If you want your text (in the text view) to be left aligned, center, or right aligned, then modify the gravity attribute of the text view.

layout_gravity and gravity have the following options:

  • for gravity and layout_gravity : here 

Here’s an example of what I’m saying:

<!-- Modifying <span class="hiddenGrammarError" pre="Modifying ">the gravity of</span> text to be center aligned, and for the text view to be center aligned (both horizontally and vertically) in the layout -->
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="@drawable/background"
    android:layout_width="fill_parent"
    android:orientation="vertical"
    android:layout_height="fill_parent"
    android:id="@+id/linearLayout">
    <TextView
        android:text="Current Location"
        android:layout_gravity="center_vertical|center_horizontal"
        android:id="@+id/textView"
        android:layout_width="wrap_content"><!--<span class="hiddenSpellError" pre=""-->TextView>
<!--<span class="hiddenSpellError" pre=""-->LinearLayout>

Note how for layout_gravity you can set for it to be aligned both horizontally and vertically by OR’ing the bits together. You could also replace “center_vertical|center_horizontal” with “center” and it would work as well. Important to note that it doesn’t work if you do “center_vertical | center_horizontal”, so spaces do matter.

Pictures will be added soon to give a visual explanation of what I’m saying.

wrap_content vs. fill_parent

The difference between wrap_content and fill_parent are both attributes which can modify the width and height of a view or layout. The fill_parent attribute sets the view/layout to take expand (either in width or height, depending on which it has been applied to) to take up all the space in the parent layout in which it is placed. If you set the width or height of a view/layout to wrap_content, it will only expand as much as its children.

If you have a text view inside a linear layout with the text attribute “Hello World”, if the width of the text view was set to fill_parent, it would expand to take up all the space (width wise) in the linear layout. If the width was set to wrap_content however, the width of the text view would only be the width required for the text “Hello World”.

<!-- Setting width and height to "fill_parent" of layout and "wrap_content" for child -->
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="@drawable/background"
    android:layout_width="fill_parent"
    android:orientation="vertical"
    android:layout_height="fill_parent"
    android:id="@+id/linearLayout">
       <TextView
            android:id="@+id/textView"
            android:text="Hello World"
            android:layout_width="wrap_content"></TextView>
</LinearLayout>

<!-- This will basically cause the root layout (linear layout) to take up <span class="hiddenSuggestion" pre="up ">the whole</span> screen, and the text view to expand only to the width of the text "Hello World" -->

Pictures will be added soon to give a visual example of what I’m saying.

I hope that was helpful, and clear enough to understand.

Setting up your environment for BlackBerry development

The first thing I tried to do after I started work was to get the same environment set up at home. I ran into some problems, but they were all eventually resolved. I’ll start by listing the steps involved (it’s really easy actually) to get it setup, and then talk a bit about why it is like this and the history.

To get it set up:

    1. You will need Eclipse. Download the most recent version of Eclipse (I believe any of them will work, although I have only tested it with Helios and Ganymede). You can download from here:  www.eclipse.org/downloads/. I used the classic version of Eclipse, not JEE, to allow for Java development as well with Eclipse.
    2. You will also need the latest JDK (1.6 at the moment). Download that here: www.oracle.com/technetwork/java/javase/downloads/index.html.
    3. You will need 32 bit Windows. You can work around it if you have 64 bit but it is a little trickier (see Problems section below).
    4. Next, download and run the JDE (BlackBerry Eclipse plugin). You can get that here:  http://us.blackberry.com/developers/javaappdev/javaplugin.jsp. Scroll down to the “Download” button with the two green arrows (it is about ~400 MB).
    5. Once that is done, go to Eclipse and Help > Install new software. Type in this url: www.blackberry.com/go/eclipseUpdate/3.6/java and hit Enter. A list will appear of the JDK you need to install, click the check box beside each and install. This installs the simulators.  For older simulators and JRE for 4.x and 5.0, repeat this step with this url: http://www.blackberry.com/go/eclipseUpdate/3.5/java.
    6. In your Environment Variables, set JAVA_HOME to the 1.6 JDK you installed in the second step. To find the Environment Variables, go to My Computer, right click Properties. Under the Advanced tab, click Environment Variables. You can edit or add new ones.
    7.  The last thing you’ll have to do is go to Windows > Preferences > Java Compiler, and set the compiler compliance level to 1.4.

That should get you set up to do some blackberry development! Have fun.

Problems

If you have a 64 bit machine, you will need to get 32 bit JDK and Eclipse if needed. This is because RIM only has the JDE available for 32 bit, as the Flash component they use only works for 32 bit machines. For 64 bit machines, you have to find a work around. You have to do the following:

  1. Download Eclipse (step 1 above has the link).
  2. Download the 32 bit JDK (step 2 above has the link).
  3. Download the JDE for Eclipse (step 4 above).
  4. Set your PATH (JAVA_HOME) variable to your JDK file location (step 6 above).
  5. Next, go to the Eclipse folder (where it was installed), right click the eclipse.exe file and under the Compatibility tab, check Run this program in compatibility mode for  and select Windows XP (Service Pack 3). Also check the Run this program as an administrator check box, then click OK.
  6. Next, go to the Eclipse installed folder, right click and select Properties>Security, and then the Edit button. Add the user that will be doing the development, then give that user Full Control by checking their name in the Allow section.
  7. If you want to import projects that worked on a 32 bit machine: File >Import >Import Legacy BlackBerry projects.
  8. The last thing you’ll have to do is go to Windows > Preferences > Java Compiler, and set the compiler compliance level to 1.4.

Signing

If you want to deploy your application, you will have to sign it, which means you will have to sign up and make a developer account with RIM, and then download their signature tool. It will provide a username/password combo which you can use to sign your application!

History

To give you a short, brief history, RIM initially had their own development environment (JDE – java development environment) for programming blackberry applications. It became terrible for developing applications that were large (a rough estimate would be greater than ~100 files), and it soon became obsolete. Currently, they work with the Eclipse plugin only. So if you see anyone telling you to only install the JDE, it’s an old post, when the JDE used to be the only way to develop for it. Now it’s simply a plugin for Eclipse.

I hope that was useful for you!

The Laws

A list of laws which I find relevant and useful (this list will be updated as I find more):

Murphy’s Law

Anything that can go wrong, will go wrong.

Conway’s Law

The structure of a software system reflects the structure of the organisation that built it.

Software Engineering Law #2: Expertise

It takes 5,000 hours of work to turn a novice into an expert. Bill Gates and the Beetles have about 10,000 hours to their name.

Hofstadter’s Law

It always takes longer than you expect, even when you take into account Hofstadter’s Law.

Clarke’s First Law

When a distinguished but elderly scientists states that something is possible, he is almost certainly right.

When he states that something is impossible, he is very probably wrong.

The difference between a great programmer and a tolerable programmer

The difference between a tolerable programmer and a great programmer is not how many programming languages they know, and it’s not whether they prefer Python or Java. It’s whether they can communicate their ideas. By persuading other people, they get leverage. By writing clear comments and technical specs, they let other programmers understand their code, which means other programmers can use and work with their code instead of rewriting it. Absent this, their code is worthless. By writing clear technical documentation for end users, they allow people to figure out what their code is supposed to do, which is the only way those users can see the value in their code. There’s a lot of wonderful, useful code buried on sourceforge somewhere that nobody uses because it was created by programmers who don’t write very well (or don’t write at all), and so nobody knows what they’ve done and their brilliant code languishes.

I [Jeff Atwood] won’t hire a programmer unless they can write, and write well, in English. If you can write, wherever you get hired, you’ll soon find that you’re getting asked to write the specifications and that means you’re already leveraging your influence and getting noticed by management.

Excerpt from this post – why good communication and writing skills are important for programmers.

Creating an executable JAR file in NetBeans/Eclipse

A simple way to create an executable JAR file using either IDE. I tried a myriad of techniques and different solutions before finding the most simple and efficient ones, and felt that they were worth sharing.

For Eclipse

A simple plugin that allows you to create a JAR file. Effective and useful.

Link

For NetBeans

Complete the following steps to create a JAR file from the Java project that you may be working on.

  1. Right click your project, and choose “Set as Main Project”
  2. Go to File > Project Properties. A box will pop up with a list of choices at the side.
  3. Under “Run”, set the main class, which will be run when the JAR file is executed.
  4. Add any libraries that need to be included with the project.
  5. There is also an option to add a splash screen, show any messages and more, under “Application”
  6. Click “OK” to save your choices and right click your project and choose “Clean and Build” (I would rather choose not to have strange problems… but if you like you can do the more quicker “Build”).
  7. Go to your project folder and inside a folder called “dist” will be the JAR file.
  8. You’re done!

Simple, easy, effective.

Basic Unix Commands

I’ve been learning Shell programming in class, and thought it would be useful to put up some of the more important commands for myself, and others to refer to if necessary.

Help with any Unix command

  • man <command>

-manual page for the command, how to use it, dependencies, etc.

  • help <command>

-works similarly as the man command, beneficial

Listing directories

  • ls

-lists the directories, and files in the current folder

  • ls <path>

-lists the directories, and files in the path location

  • ls – l (or with <path>)

-lists the date, size, and permissions of the directories and files in the current location

  • ls – a

-lists all files, including .dot files (which remain hidden otherwise)

Changing to a directory

  • cd <dirname>

-changes to given directory if it is a child of current directory

  • cd ..

-goes up one level, to the parent directory

  • cdup

-works in the same way as “cd ..” (goes up one level to the parent directory)

  • cd ~

-goes to home directory

Making a new directory

  • mkdir <dirname>

-creates a new director with

Removing a directory

  • rmdir <dirname>

-removes directory iff is empty

  • rm -r <dirname>

-removes directory and all subdirectories and files

Making a new file

  • vi <filename>

-write whatever you like, and you can save it. VIM is the provided text editor.

  • cat > <filename>

-write whatever you like and press Ctrl+d to save (can enter multiple lines)

Remove a file

  • rm <filename>

-removes a file

Renaming a file

  • mv <oldfile> <newfile>

-renames file <oldfile> to <newfile>

Copying a directory

  • cp -r dir1> <destinationPath>

-recursively copy directory <dir1> and all subdirectories to <destination>

  • cp <file> <destinationPath>

-copies file <file> to destination <destinationPath>

Viewing text files

  • more <filename>

-view file, one screen at a time

  • cat <filename>

-view file, allows scrolling

  • vi <filename>

-vi is the VIM text editor, allows you to view the file

Editing text files

  • vi <filename>

-comes with the Bourne shell. Emacs and others are also available.

  • cat <newfile> >> <otherfile>

-appends file <newfile> to <otherFile>

Other text commands

  • grep ‘<pattern><file>

-find the <pattern> in <file>

  • wc <file>

-count words in file <file>

Pipes and redirection

  • <command> > <file>

-redirect output to a file

  • <command> >> <file>

-append output to existing file

  • <command> < <file>

-get input from a file

  • <command1> | <command2>

-pipe one command to another

Permissions

The properties of a file or directory are as follows:

uuugggooo (meaning, the first three permissions are for the user, the next three for the group, and the last three are for the world, or others).

The user, group, and world all have rwx (read, write, execute) permissions, in that order. To view permissions,

ls -l

The first character in the properties line will be either a “-“ or a “d”. A “-“ means it is of type file, and “d” means it is a directory. So the entire formation would look something like:

-rwxr-xr-x                           or

dr——-x

The first is a file, the second is a directory. To change permissions do:

  • chmod u+rx <filename>

-gives the user read and write permissions for the file <filename>

  • chmod a+rwx <filename>

-gives everyone read, write, and execute permissions for file <filename>

  • chmod u-x <filename>

-removes execute permission from the user for file <filename>

I found myself using these the most frequently, but if you need more help or direction check out the following:

Linux Journal
Linux Help
Linux Questions
Excellent list of all UNIX commands