Sunday, April 24, 2011

Simple Backends for Android Apps - Part 1

        In my recent lunacy I decided to take up my friends offer and work with him on a multiplayer android game. It's a dice game, but we hope that people will give it a chance since it's very addicting. I'm currently suffering from Feature Rampage, and I'm deciding to add complex features before I'm done implementing simpler ones. It's a terrible business practice but considering that we specified no budget for this and that we are doing this part time, I don't care ;) One of the features that I decided to implement was online play (including friends and chats)! It's pretty ambitious considering this is going to be the first product I ever made and that I don't know any html, http or any other language besides Java. What can I say? I learn best by doing : D

       For this post I won't dabble too much into the details of the framework, instead I'm going to provide an overview and explain how I implemented push notification for android versions 1.6+.

       Since we already established that I'm a n00b at everything (I dropped the hint in the Blog name btw) I set out on Google's Blue, Green, Yellow, and Red road to find the right assets for me and my current needs. My criteria was simplicity, reliability and speed. Simplicity because I want to release this app before I get out of High School, so while I would love to read and learn about new technologies it wouldn't fit the schedule. I wanted reliability because I didn't want to re write the whole app because I chose the wrong service; I would rather take my time choosing that waste my time switching services. And lastly I wanted Speed because frankly who likes to use slow, unresponsive apps?

       Still here? I'm surprised you care that much!...erhmm....right! backends...I happened to mention that I wanted push notifications. I basically want to avoid polling for anything. I'd Rather put a load on a server than on a user's phone. I couldn't use Android's C2DM because I would be leaving almost 30% of Android Users       without Push, so XMPP ( or Jabber for you old timers) seemed like the perfect match up for me. After all, C2DM is based off of XMPP! I just needed to copy it.

     I set out to make my own XMPP server and after numerous failed attempts I found this wonderful service called XTIFY. It was a blessing! Saved me a ton of work and I have not had a single dropped notification. Don't be fooled, while the site heavily pushes developers to use their pre-made Notification Activity you can send a "custom" notification with your own custom intent in it. Like so:

In XTIFY you can add your custom intent



And in your code add this:



Btw this is assuming you followed the implementation guide (which is fairly good!)

From this central Broadcast Receiver I can organize and send intents to other activities, write to databases and just treat this like a response from a server without having to deal with stupid http requests. That's going to come in the next part of this series ;)

Saturday, April 16, 2011

Android Animation Bug

After much head bashing I have found a bug in Android. Now I wouldn't be posting it here if I thought it was a big enough bug but I'm sure most of you will encounter it if your using the android.view.animation package. I'm also positive it's a bug because there are tons and tons of animationListener questions on StackOverflow. So there are many variable to make this bug happen so I won't go into the procedures to recreate it. I'm going to keep it Short and Simple and tell you this. If you ever do this:

Animation a = AnimationUtils.loadAnimation(this,R.anim.translate_animation);
a.setAnimationListener(new AnimationListener(){
        @Override
public void onAnimationEnd(Animation animation) {}
        @Override
public void onAnimationRepeat(Animation animation) {}
@Override
public void onAnimationStart(Animation animation) {}
});

And you figure out eventually that any of the onAnimation* methods never get called, then you ran into the bug.

So far the only solution that I found was to make a subclass of the view that you're using and override the onAnimationEnd method with whatever you want to do. Like this.

Shoutout to Matt Quigley. He's a software engineer that works on mobile phones. Follow his blog and his excitement on Android Engineer

Design before Code

        There's this image of the ultimate programmer that no doubt, at least, will flash through the newbie programmers mind. He's a genius, no doubt wearing glasses, he writes code by himself, he doesn't write bugs--ever, and he doesn't plan before coding (after all the code he excrements exceed the value of John Carmack's code). Now the first quality surely helps at programming but the rest are superfluous or just plain wrong. No one cares if you wear glasses or not. EVERYONE makes bugs, its natural because we're human beings and we make mistakes. And (depending on the size of the project) no one-I repeat- NO ONE can code all alone or start coding before designing a good bit of the structure.

Today I'll talk about the designing part of programming. I'm working on a dice game for Android and during the early stages of the game I made a class that you send an int Array (int[]) and it will return the highest score possible of that group of dice. While I was designing the class, it occurred to me that it was the perfect situation to use a Final Class. There was no instance dependency anywhere in the class and all the methods could have easily been static. BUT!, being the lazy person that I am I decided to make a regular class that used variables to keep track of the number of dice face values i.e. numOf1 = 3 implies that in the array there are 3 ones. During the development I kept having to change a lot of the code of the other classes to accommodate for the shortcomings of the class. For example, I forgot that since I used 1 instance the state of the variables were never reset to 0 after the class calculated the score of an Array. Little mistakes like these forced to make the class Final and all the methods in it static, which looking at it now makes the whole project A LOT easier.

What Am I driving at here? Well basically, all that hardship could have been avoided if instead of being lazy I stopped coding for a moment and thought about the future of the project. But I didn't. I love to code and while I was coding I was in the ZONE. You know how it is. Its like a vice. You feel omnipotent. I did and I didn't want to stop to think about the design of the structure. And it cost me. Getting in the zone is often regarded as when you get the most work done or the most important work done. Sometimes getting out of the zone and into design mode can help a lot more.

My shout out for this post goes to Joel Polsky who works at Fog Creek Software. He's very a very smart down to earth man who's blog post give a lot of advice based on a good bit of experience. This blog post should speak for him better than I ever will be able to ;-) Until next time. Follow me on twitter @tytdfn to send me suggestions or questions.

Saturday, April 9, 2011

More on Hg (Aka Mercurial for Dummies)

Remember that tutorial on Easy App Project Hosting?  Yeah well if you followed it, I basically tricked you into implementing Code Revision software into your project. It's a good practice since it enables you to

  1. Share your code easily
  2. Work with other programmers at the same time
  3. Fix any mistake by reverting back to old versions of files
  4. Keep you code backed up

And if you followed the tutorial to the letter, you're currently using Mercurial (or Hg) as your code revision control system. Allow me to explain myself further. IFF (if and only if for those math noobs) you don't care and want a quick crash course on Hg scroll down.

BIG WARNING: If you choose to use Google code for project hosting remember that anyone in the world can look up your code. Google code is only suitable for Open Source Projects

1. Share your code easily
  • For someone to take a look at your code its as easy as "hg clone [url]" 
    • This command will download the whole project located at [url] and make a local copy on the users computer. The user will even be able to make changes to the code and commit to their local repository.
  • Make branches so your work and your colleague(s) work is separated. 
    • It's still easy to see each other codes, especially if you use Mercurial Eclipse. To make a branch go to your project, right click on the project Team>Add Branch. To see the work of your colleague(s)on another branch right click on your project again and Team>Switch To
  • Wanna take a peak at the code from anywhere in the world?
    • Your code can be viewed directly from your Google Project website in case you brainstorming a problem and you want to refresh your memory.

Before I move to point #2 I want to point out that this sounds like a really generic attempt to promote these services. I'm not affiliated with any of these companies, I just love using these tools so much that I feel like blogging about it. I guess thats enough to classify me as a nerd hehe.

2. Work with other Programmers at the same time

How is this possible you might ask? Well Hg has this cool feature called merge. You and your colleague(s) can work on one thing at the same time (even in the same branch) and when it comes time to join your work together, you use the merge tool. The merge tool works like this
  1. Import the work you want to merge.
  2. Use the merge command. Either through a command line (hg merge) or by Team>Merge
  3. When there are conflicts choose which files/parts to keep. Some Scenarios include
    1. Keep file a ,b and choose your colleagues(s) c
    2. Keep file a, use your colleagues(s) b, and use method 3 from your colleague(s) c file instead of your own.
    3. Your colleague(s) is a genius keep all his files and cry yourself at night

3. Fix any mistake by reverting back to old file revisions.

Oops wrote 300 lines and I broke the build. Hmmmm I don't feel like going through all of the code again. It came out kinda messy. Geee I wish I could just turn back time and start over from where i left the code off yesterday....WAIT A DARN MINUTE! I can just right click on the said file and  Team>Revert to yesterdays revision of the file hehehe. Sweeeet! Now I can pretend to bug track while I look at some youtube videos....


4. Keep you code backed up

NOOOOOOoooooo! I accidently deleted the project yesterday after that crazy party....beer and programming don't mix....oh yeah I pushed all my changes up the google code project site. Now just File>Import>Mercurial>Clone Existing Mercurial Repository . Ok while that loads I can just.....oh its done.


Hopefully that illustrates why a modern programmer would LOVE code revision control. I know I do. Heres some helpful hints

----------------STOP SCROLLING HERE IF YOU WERE TOO LAZY TO READ MY POST----------

Quick Explanations of Commands:

Pull - "pulls" in new versions of the code
Update - overwrites old code version with new code version
Commit - save the state of your code to your local repository
Push - "push" all the commits up to your project hosting website
Synchronize - check to see if there are any new code revisions in the project hosting website
Merge - to merge you need to have different versions of the same file in your local repository -or- choose to merge with another branch.
Add Branch - pretty self explanatory...except I would like to add that branches are very useful

Also I'm starting to refer you to other cool programming blogs. I'll start with Kaloer. He's a very respected android developer and I hope to make blog posts as useful as his in the future. Click here for his blog


Wednesday, March 30, 2011

Beautiful Code: Pt. 1

***I'm starting this new series which will highlight code that I think is pretty/gorgeous/mind-blowing or all of the above. Generally it will be simple cases, and most of it will be Java only because of my limited knowledge of coding languages. Feel free to submit code to me (Using Pastie works best I believe) or to correct code highlighted in these segments.***

findPairs()

I'm making a dice game for android with a close friend of mine. The game is called Farkle and its highly addictive. A player needs to roll 6 die and choose the best combinations to score the most points. This method I just created will return the positions of other dice with the same value. The method came out very clean and I'm extremely proud of it. Even if it's extremely simple

public int[] findPairs(int index, int value) {

      int[] dirtyArray = { 0, 0, 0, 0, 0, 0 };
      int count = 0;

     for (int j = 0; j < dieValues.length; j++) {

            if (j != index && dieValues[j] == value) {
                  dirtyArray[count++] = j;
            }
     }

    if (count == -1)     return null;
    int[] cleanArray = new int[count];
    System.arraycopy(dirtyArray, 0, cleanArray, 0, count);
     return cleanArray;
}


Edit: Teehee made a mistake and just found it. Guess that's what happens when you post "Beautiful" code before testing. Note to self: variable++ returns the variable before it got incremented


Double Edit: And another one! It's perfect now (I promise)

Sunday, March 27, 2011

Another Reason for Admob Ad's to not load and the Virtues of the Logcat

The Admob library for Android can be a bit of a pain to get it to work sometimes. Today I learned a valuable lesson: Don't put padding on the Layout where the ad will go OR THE AD WON'T SHOW UP. Unless you know how to use the logcat for android, this will be a very hard problem to solve.

Since were on the topic of logcat  here's a helpful hint if you're using Eclipse. Instead of opening up a cmd (command) line to look at the logcat and typing in "adb devices" then "abd shell" then "logcat"just go to Eclipse

Window>Show View>Other> then look under the Android Tab and double click on the Logcat View And viola!

Wednesday, March 23, 2011

Easy Android App Project Hosting with Eclipse and Google Code

One of the things I love about Google is all the different kinds of services that they offer to users, and the fact that I only need to remember my Gmail login to access all those features. One service I find particularly useful is Google code. It allows me to develop on different work stations and also helps me and my coding friend(s) keep connected no matter where we are.

This tutorial expects Android and Eclipse to be installed on the system.

So if your interested comon' and follow me. I'll Show Ya!


1. Set up a project.
  • Go Here and make a new project. *Choose the version control as Mercurial* <-very important
2. Create a new Android App Project in Eclipse
3.Install the Mercurial Eclipse Plug-in

4.Make a local Repository
  • Right Click on the new Android App Project (1)
  • Team (2)
  • Share Project (3)

  • Click On Mercurial
  • Next
  • Click on Next until you can click on Finish
5. Synchronize with the Goggle Project you set up in the first step.
  • Go to the homepage of the Project. Click on Source
  • Keep this page open. Your gonna need to use the info here shortly.
  • Open up Eclipse
  • Right Click on the Android Project you made 
  • Team
  • Synchronize with
  • Next (1)
  • Now the URL is the one shown on the Checkout Tab of your Project Host (after hg clone) (2) 
  • The username is your Gmail (3)
  • The Password is shown when you click on the google.com password link (4 & 5)
  • Next until Finish
6. First Commit! (Almost There!)
  • Right click your project (1)
  • Team (2)
  • Commit (3)

  • Check Select All (1)
  • Put in "Project Start" for the Commit Message
  • Ok

7. PUUUUUUUUUUUSH! *Grunts* wait its not that hard!
  • Right Click on Project (1)
  • Team (2)
  • Push (3)
  • Finish (4)

8. TA DA!
  • Go to your Project Homepage
  • Click on source
  • Now you can either Browse through you project files or
  • See your Changes 

10. Wait a minute!

    You probably want to know how to have your work show up in other computer that you wanna work on (Which already have Android ,Eclipse ,and the Mercurial Eclipse Plug-in installed already) Easy!

(Try this on another computer if you want can to see some magic happen)
  • Go to Eclipse
  • File (1)
  • Import (2)
  • Clone Existing Mercurial Repository (Under the Mercurial Tab)
  • Next

  • Now just put in all the info that you put in when you Synchronized the Local Repository to the Google Project website.


Now you can keep your project synced between colleagues, or just between your different workstations. When you wanna save some work just Team -> Commit and when you wanna sync it with the Project Hosting just Team -> Push


PS: Write any suggestion in my comments or contact me on twitter: @tytdfn



Android: "Smart Folders"

I love clean code. One of the features android has that makes it easier to write clean code is a feature I nicknamed "Smart Folders". Take for example this scenario: You would like your application to have different layouts based on the screen orientation. Your first try might look something like this

public void onCreate(Bunde icicle)
{
       super.onCreate(icicle);
       int orientation = getResources().getConfiguration().orientation;
       if (orientation = Configuration.ORIENTATION_PORTRAIT)
       {
              setContentView(R.layout.main_port);
        } else if(orientation = Configuration.ORIENTATION_LANDSCAPE)
       {
             setContentView(R.layout.main_land);
       }
}

Then you stumble across this post and magically your code turns into this:

public void onCreate(Bunde icicle)
{
       super.onCreate(icicle);
       setContentView(R.layout.main);
}

You ask how is this possible? Simple: Android at runtime checks the configuration of the phone and looks in your /res folder for matching Resource Directory Qualifiers and uses the correct resources accordingly. WHAT THE HECK DOES THAT MEAN?   I hear you sayin'?

It means that if Android detects that the phone is in landscape mode it will check the /layout-land directory/folder for the main.xml . If it can't find a match then it defaults to checking the regular layout folder. Not only does this make your code easier to read but it will also make it more manageable down the road.

For a list of all the qualifiers android offers look Here (Scroll down a little to see the table) 
Some of the qualifiers include

  • Language and region: So you can Localize your strings
  • Screen size and/or Screen pixel density (dpi) : So your app looks good on any screen
  • Keyboard availability: So you can control when to show the soft keyboard
  • Primary non-touch navigation method: So you can support trackballs and trackpads!


TL;DR:
1. Put main_port.xml in the /layout  directory/folder
2. Put main_land.xml in the /layout-land directory/folder
3.Rename both xml's to main.xml

Piece of Cake! Next Post will be a tutorial on how to set up your app project with a new Google Code Project and how to easily sync your code to your project with the Mercurial Eclipse Plug-in. Please Stay tuned and pass this around.

PS: Write any suggestion in my comments or contact me on twitter: @tytdfn