Tuesday, December 15, 2009

Customize Toast Messages in Android

Since I've started developing for the Android platform, I've found Toast messages to be extremely useful. They are simple to instantiate, and look very sleek. Some instances though, wouldn't work with a Toast message because of the nature of their message. An error or notification doesn't seem adequate for a Toast message. Primarily because those types of messages need to grab the users attention, and most often use colors like red or yellow.

I wanted to use the Toast message for a notification, but wanted a yellow background instead. So, I wrapped the static toast method, makeText, with another static class that looks like this..

...


public static void show(Context ctx, String message, boolean notify) {

     Toast t = Toast.makeText(ctx, message, Toast.LENGTH_LONG);
     // if the message is a notify, modify the Toast view

     if (notify) {
            int offset = 100;

            // get the layout, center it, and change the background
            LinearLayout layout = (LinearLayout) t.getView();
            layout.setGravity(Gravity.CENTER);
            layout.setBackgroundResource(R.drawable.toast_frame_yellow);
            // get the text view, change the color, and make it narrower
            TextView tv = (TextView) layout.getChildAt(0);
            tv.setTextColor(Color.BLACK);
            tv.setGravity(Gravity.CENTER);
            tv.setMaxWidth(ctx.getResources().getDisplayMetrics().widthPixels - offset);
      }
                                                                     
      t.show();
                                                                      

                                                                        
}                                                                     

                                                                                                                                           

...


Most of this explains itself. The new background drawable that I used is the btn_default_pressed.9.png image, which is available in the Android source code. I chose this in order to save time. It's already a yellow/orange tone, and it's a 9-patch, so it'll stretch nicely. The maxWidth was changed in order to make the Toast view narrower...just a personal preference.

Here's the end result...


Wednesday, December 2, 2009

Drrrroid does

Contrary to my previous post, I really really like developing on the Android platform, especially for version 2.0. I have a few projects going on that I will post about shortly, including a "pinch-zoom" View!

Here is a link to the Google Code project;

android-pinch

Monday, October 26, 2009

My First Android Experience...meh.

My current interest is Android development. I've put all of my other projects on hold for this too! This isn't the first time I've done Java, in fact I have done a lot of Java before. The thing is though, that I don't remember the last time I had to use sooo much XML! Maybe never. JSON has been apart of my development life for years now, and it's always given me a feeling of resentment towards XML. It's too clunky and bulky, like a rusty old machine.

Maybe I'm just looking at it with the wrong set of eyes. As a web developer, XML means extra overhead, no built-in data types, large file sizes, extra parsing, and non-native support (in most cases). So beginning my first serious Android project, I'm hating XML before I get the chance to understand it's true potential. Truth be told, I'm starting to see how great it can be for certain instances.


Is it just me, or do Java developers love them some XML??? They may be the only ones keeping it alive; they're also keeping Java from getting buried, so they may be used to it. (jk)

I will say that it is very cool to be able to create an entire layout in one XML file! It's extremely versatile, and super flexible. One can change the Look & Feel without having to go into any code. Great! The major headache with this though, is the learning curve. For instance; the widgets, their attributes, layout types, and all of the different pieces used to put these applications together. Like; activities, intents, providers, services, and adapters. Mamma mia!!

Okay, these concepts are not completely foreign to me, having done Java before, but I guess it's been awhile. The structure and elegant design patterns have always intrigued me. In fact, I apply a lot of those patterns within my web applications. Though, sometimes enough is enough. Don't make it complex for the sake of being complex.

So far though, I do prefer iPhone development over Android. The tools that Apple gives you are insanely easy to use. I'm not a designer, so I don't want to spend all of my time on the UI, and using the interface builder, I can easily get most of the Look & Feel taken care of, so that I spend my time where it matters...coding!

Also, one can harness the power of C/Objective-C for their apps. Mmmmmm, speed. While going through Android tutorials, I was a bit discouraged when I saw articles titled, "How to optimize your Android loops", or "How to design for performance". Seriously?!?! I haven't even started yet, and I have to worry about that? I already optimize the hell out of anything that I make, but telling me off the bat that the application is going to need to be optimized is a bit sad. Oh well, it's Java, so what should I have expected?

I'll keep updating this as the project progresses. Perhaps my opinions will change!


PS - I'm aware that Android !== Java, so don't waste your time.

Wednesday, October 14, 2009

Threading in JavaScript with Web Workers

One of the things that I love about lower-level programming languages like C/C++, and even Java, are the fact that you can thread off new processes in the background. Since a lot of my work involves creating web applications, I work with JavaScript a lot. It really got to me that everything is single-threaded. I'm embarrassed to say that I haven't really read much on Web Workers until recently, but once I learn about something as great as this, I must make it my own! I scoured the web for examples and specs, until I had my fill. While the implementation is great for the web, and will bring about even better applications, I did not like the interface that it was presented in.

I always loved the simplicity of Java Threads, so I felt inclined to create a decorator for Web Workers that would give it a Java Thread interface. This will consist of a Thread object that  runs an object of type Runnable, in the background.

UPDATE: The cross-browser implementation is finished! Go ahead and knock yourselves out.

You can check out the work in progress here;

JSRun

The implementation seems simple enough to me, but I'm curious as to what others might think.

Monday, September 14, 2009

Facebook Puzzles

Programming is like an art. If you don't practice you cannot evolve. I've been doing web applications for a few years now, with a little bit of actual software development in between. So, it was nice to have a challenge and try out a Facebook Puzzle. You can find them here. They're available in all different flavors, with a hierarchy of difficulty levels. I chose to try out dinoisland. Why not, right? Let's get into the good stuff, no need for the hors d'oeuvres.

To get setup, I had to install Thrift. That way, the actual code library could be compiled in, pretty much, whichever language I desire. Initially, I started with PHP, because that's what I've been using a lot lately, and I feel as if I've close to mastered it ;) I found difficulty with it because it seemed as though it lacked power, especially for a client that I knew would need to be threaded. After a day with PHP, I gave up, and switched over to Java. What a relief! Aside from the AI part of this puzzle, it felt like this project was meant to be programmed in Java. If I knew LISP, then I would have used that, but...meh, I'm busy right now with the puppy and work.

My approach for the Java application was to divide the solution up into different portions;
  • Client - connects to the server and creates an instance of our dinosaur, then threads it off to do it's own thing.
  • NPC - This would be our dinosaur, a non-player character. This guy handles it's own state, communicates with the server directly, and decides it's next moves. There is also a history object which contains all of it's recent actions, and path history.
  • ActionFactory - We are allowed 4 different actions in this puzzle; move, grow, look, and egg. Their is a handler for each of those actions, and the AF abstracts the process of handling those, and determining a result.
  • Action Handlers - The handler analyzes the result from the server, and returns the current state. It also determines a suggested next action, based on the results it receives.
  • ResultAction - a simple class created in order to store valuable info about the dino's actions.
  • Directions - Methods were added to help with navigation. For example, if my dino needed to turnLeft, turnRight, turnAround, or even go in a random direction.
  • History - keep track of our actions, and our movement history.
This is how the basic structure was. I had a grandiose idea in my head of creating a dino that would look, cache the results, and based off of those, decide which areas were the best to venture towards, or moveTo. Also, having the path history static would help new dinosaurs with their movement decisions.

As it turns out though!! None of that was necessary. While still testing, brute force, and strength in numbers seemed to be adequate enough. I had my dino's grow to level 2 instantly. This way, they could eat more plants, gain more calories, and be less susceptible to getting beat up. The only logical pieces implemented were;
  • if your movement returns false, turn to the right (if we hit a rock or big plant)
  • if we have n number of calories and are a size s, we should grow
  • if we have n number of calories, let's lay an egg
I was able to achieve a score of 124,750 with that simple bot. Honestly, just lay as many eggs as possible with enough calories to keep them alive. Of course the downside of this solution is that it is not consistent, and relies on probability. Many things must go right for it to succeed....and succeed it did!

Thursday, September 10, 2009

jQuery rounded corners for images!

Rounded corners have been popular for along time now. I can remember over 3 years ago, checking out Stu Nicholls website for his killer CSS tricks with boxes and other things. Images, though, always required the effect to be produced prior, and couldn't be done dynamically. Flash helped with that, but do you really want to use Flash all the time, or just for an image? A couple of months ago I created a plugin for jquery that will round your corners, and then some! Here is a feature list;
  • rounder corners w/ adjustable radius
  • border w/ adjustable width and color
  • drop shadow w/ adjustable position, color, opacity
  • image scaling
  • image positioning
  • 2K in size, minified (for those of you who do not gzip your content)
Here is a sample image to give y'all a taste...



From left to right; it's the original image, rounded image, and scaled/rounded image with border and shadow effects. There have been some requests to apply this to any HTML element, although that may come if this grows in popularity.

Here is in example of how it can be used within a page:

<html>
    <head>
    </head>
    <body>
        <img src="img/sample1.jpg" class="round" alt="Sample 1" /><br/>
        <img src="img/sample2.jpg" class="round" alt="Sample 2" />
        <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
        <script type="text/javascript" src="js/dropCurves.js"></script>
        <script type="text/javascript">
        $(document).ready(function() {
           $("img.round").dropCurves({
                w:500, // scale image to width 100px
                h:500, // scale image to height 120px
                bSize:2, // 2px border size
                bColor:'#000', // black border
                sColor:'#333', // shadow color
                sX:-3, // shadow offset X
                sY:3, // shadow offset Y
                o:0.5, // shadow opacity
                r:10 // corner radius
            });
        });
        </script>
    </body>
</html>


Like what you see? You can get it here!

http://plugins.jquery.com/project/dropcurves


Feedback??

Thanks!

Thursday, September 3, 2009

Textmate FTP/SSH bundle with Snow Leopard

I love to develop with textmate, and I love to work within the Mac OS X environment, so when I heard Snow Leopard was coming out, I thought, "Hey, why not?". Well, I soon found after upgrading that my local dev environment wasn't working as it had. This was because PHP 5.3 comes preloaded with Apache, and it needed to be set up...again. Ok, not sooo bad. Soon after, I was working on a remote project, in TextMate, and do the same old Option+S, to save to the server, and realize that I'm getting PHP Notices, and a Fatal Error! After some searching on the web...I found nothing. Damn! Time to use the old ticker, and figure it out for myself :( I soon discovered that the PHP super global variable $_ENV was no longer being populated with the correct Textmate values. The fix required that $_ENV be replaced with $_SERVER in the bundle commands, and in the helper_functions.php. Voila! Textmate is back to it's prior glory, and I don't resent Snow Leopard anymore...for now.