Posts Tagged ‘ Implementation ’

Enumeration and arrays

Recently, I discovered the usefulness of the enum type in C++. I can’t believe how long I’ve gone without using an enum because I didn’t know why I should use it over a #define. The two main reasons to use enums over #define is 1) sequential self-numbering and 2) enums allow the value to be visible to the debugger. This post is about the first reason.

Let’s say we want a list of variables, and the variables need to be assigned a unique number for processing, but we don’t care what number is assigned to it. Enumeration to the rescue! Define an enum with a list of variables and it will assign each variable an integer value starting from zero. For example:

enum
{
    alpha,
    beta,
    delta,
    gamma
};

// The values stored in the enum variables are:
// alpha == 0
// beta == 1
// delta == 2
// gamma == 3

Now you can add another variable to the the list in any position (because remember we don’t care what number is assigned to it, it just has to be a unique number) and you won’t have to renumber the other values. It just does it automatically!

enum
{
    alpha,
    beta,
    omega, //<---------
    delta,
    gamma
};

// The values stored in the enum variables are:
// alpha == 0
// beta == 1
// omega == 2
// delta == 3
// gamma == 4

You’re probably thinking: “Great, it self-numbers. What’s the point?” Well the point is that you can use this as array indices and declarations. Assume you have some boolean option settings for your program with the following options: isFullScreen, isWidescreen, isMoving.

Let’s start out making a new file called “options.h” with the following code:

namespace options
{
    enum
    {
        isFullScreen,
        isWidescreen,
        isMoving,
        size
    };
}

I put the enum inside a namespace so that I can use the enum in multiple places without creating an instance of an object. The namespace also allows Visual Studio to list all the enum variables in the autocomplete dialog when using the scope operator ("::"). All I need to do is add #include "options.h" to the top of the header files where I want to use this enum. The last variable size is always going to be the size of the array. Now, remember an enum variable is a const integer value which is why we can use it as an array index value. To use this enum in a class I would use the following code snippet:

// include the namespace file
#include "options.h"

// declares the array, but does not initialize the elements
bool myOptions[options::size];

// then I can initialize the values like so:
myOptions[options::isFullScreen] = false;
myOptions[options::isWidescreen] = false;
myOptions[options::isMoving] = false;

...

// usage example
if(myOptions[options::isFullScreen])
{
    // do something
}

That’s fine and dandy, but if we add another option, we would have to add another line to set that option to false on initialization. We’re lazy and are willing to write more code now to prevent having to write more code in the future so let’s add a reset function to the options namespace.

namespace options
{
    enum
    {
        isFullScreen,
        isWidescreen,
        isMoving,
        size
    };

    static void Reset(bool myArray[options::size], bool value);
}

// the following lines of code are in the same file as the namespace
/**
@brief Resets all the options to a specific value
@param myArray  The array of options using the namespace's enum
@param value    The value to assign to all the options
*/
void options::Reset(bool myArray[options::size], bool value)
{
    for(int i=0; i<options::size; i++)
    {
        myArray[i] = value;
    }
}

I put a value as a parameter because I want the flexibility to set all the options to true or false. The static keyword allows us to use the function without declaring an object so we just reference the function like so in the class:

// declares the array, but does not initialize the elements
bool myOptions[options::size];

// resets all the options
options::Reset(myOptions, false);

...

// usage example
if(myOptions[options::isFullScreen])
{
    // do something
}

Now let’s add another option to the enum to detect if a file is loaded:

namespace options
{
    enum
    {
        isLoaded, //<-----------
        isFullScreen,
        isWidescreen,
        isMoving,
        size
    };

    static void Reset(bool myArray[options::size], bool value);
}

The beauty of this is I can add this function without having to renumber or edit the existing code! I just add the new option where I need to use it.

// still works correctly
if(myOptions[options::isFullScreen])
{
    // do something
}

// do this for the new option
if(myOptions[options::isLoaded])
{
    // do something
}

This is not the only example for using enums with arrays. There are so many possibilities such as having an array of strings and looping through it to read the values. Learning how to use enums for arrays changed my life. It has made me more productive and made maintenance so much easier. It’s such an elegant, cheap, and easy way to improve the code tenfold.

Advertisements

How to shoot yourself in the foot in any programming language

Searching through the documents on my hard drive this weekend I came across a document containing the joke of how to shoot yourself in the foot in any programming language. Well, not literally, but it does relate how the different languages behave by using the analogy of shooting one’s self in the foot. I forgot where I found this so if someone knows, post the link in the comments!

* * *

How to Shoot Yourself in the Foot in Any Programming Language

The proliferation of modern programming languages (all of which seem to have stolen countless features from one another) sometimes makes it difficult to remember what language you’re currently using. This guide is offered as a public service to help programmers who find themselves in such dilemmas.

C
You shoot yourself in the foot.

C++
You accidentally create a dozen clones of yourself and shoot them all in the foot. Providing emergency medical assistance is impossible since you can’t tell which are bitwise copies and which are just pointing at others and saying, “That’s me, over there.”

JAVA
After importing java.awt.right.foot.* and java.awt.gun.right.hand.*, and writing the classes and methods of those classes needed, you’ve forgotten what the hell you’re doing.

Ruby
Your foot is ready to be shot in roughly five minutes, but you just can’t find anywhere to shoot it.

PHP
You shoot yourself in the foot with a gun made with pieces from 300 other guns.

ASP.NET
Find a gun, it falls apart. Put it back together, it falls apart again. You try using the .GUN Framework, it falls apart. You stab yourself in the foot instead.

SQL
SELECT @ammo:=bullet FROM gun WHERE trigger = ‘PULLED’;
INSERT INTO leg (foot) VALUES (@ammo);

Perl
You shoot yourself in the foot, but nobody can understand how you did it. Six months later, neither can you.

Javascript
You’ve perfected a robust, rich user experience for shooting yourself in the foot. You then find that bullets are disabled on your gun.

CSS
You shoot your right foot with one hand, then switch hands to shoot your left foot but you realize that the gun has turned into a banana.

FORTRAN
You shoot yourself in each toe, iteratively, until you run out of toes, then you read in the next foot and repeat. If you run out of bullets, you continue anyway because you have no exception-handling ability.

Modula2
After realizing that you can’t actually accomplish anything in this language, you shoot yourself in the head.

COBOL
Using a COLT 45 HANDGUN, AIM gun at LEG.FOOT, THEN place ARM.HAND.FINGER. on HANDGUN.TRIGGER and SQUEEZE. THEN return HANDGUN to HOLSTER. CHECK whether shoelace needs to be retied.

LISP
You shoot yourself in the appendage which holds the gun with which
you shoot yourself in the appendage which holds the gun with which
you shoot yourself in the appendage which holds the gun with which
you shoot yourself in the appendage which holds the gun with which
you shoot yourself in the appendage which holds ….

BASIC
Shoot yourself in the foot with a water pistol. On big systems, continue until entire lower body is waterlogged.

FORTH
Foot in yourself shoot.

APL
You shoot yourself in the foot, then spend all day figuring out how to do it in fewer characters.

Pascal
The compiler won’t let you shoot yourself in the foot.

SNOBOL
If you succeed, shoot yourself in the left foot.
If you fail, shoot yourself in the right foot.

Concurrent Euclid
You shoot yourself in somebody else’s foot.

HyperTalk
Put the first bullet of the gun into the foot of the left leg of you.
Answer the result.

Motif
You spend days writing a UIL description of your foot, the trajectory, the bullet, and the intricate scrollwork on the ivory handles of the gun. When you finally get around to pulling the trigger, the gun jams.

Unix
% ls
foot.c foot.h foot.o toe.c toe.o
% rm * .o
rm: .o: No such file or directory
% ls
%

Paradox
Not only can you shoot yourself in the foot, your users can too.

Revelation
You’ll be able to shoot yourself in the foot just as soon as you figure out what all these bullets are for.

Visual Basic
You’ll shoot yourself in the foot, but you’ll have so much fun doing it that you won’t care.

Prolog
You tell your program you want to be shot in the foot. The program figures out how to do it, but the syntax doesn’t allow it to explain.

Ada
After correctly packaging your foot, you attempt to concurrently load the gun, pull the trigger, scream and shoot yourself in the foot. When you try, however, you discover that your foot is of the wrong type.

Assembly
You try to shoot yourself in the foot only to discover you must first reinvent the gun, the bullet, and your foot. After that’s done, you pull the trigger, the gun beeps several times, then crashes.

370 JCL
You send your foot down to MIS with a 4000-page document explaining how you want it to be shot. Three years later, your foot comes back deep-fried.

Python
You try to shoot yourself in the foot but you just keep hitting the whitespace between your toes.

Writing and getting variables from Windows registry

MFC makes it easy to use the Windows Registry to store your application’s settings and variables. This allows your application to retain last used options, recent files, preferences, colors, fields, whatever. I’m assuming that you can use Visual Studio’s new project wizard to make a new MFC application/project.

I am using Visual Studio 2008 SP1 on Windows Vista 32-bit as of the writing of this article.

In the main cpp file that is generated, find the InitInstance() function. In this function, there should be a function call to SetRegistryKey. This function takes in a LPCTSTR (which is a long pointer to string) and you can just give it any string (Microsoft recommends using the company name here). I would use it like this:

SetRegistryKey(_T("My Fookin Company"));

The “_T()” part is just a macro that converts the string to a LPCTSTR. This line is all you need to set your program to use the registry. If it isn’t in InitInstance(), then just add it.

To save information to the registry, you would use the following code:

// get the current application object
CWinApp* pApp = AfxGetApp();

// This is the string I want to save
CString engrName = "Alex";
int age = 24;

// "ArbitrarySectionName" is the collection of information to store (if you have multiple sections in your application such as "userProfile" and "userSettings" then you would use those different names)
// _T("engrName") is a variable in the registry. you create this here so you can name it "foobar" for all it cares
// just remember what you named it so you can get it later
// engrName (the last parameter) is what you're saving (in this case, it is the string "Alex")
pApp->WriteProfileString(_T("ArbitrarySectionName"), _T("engrName"), engrName );

// let's just save an integer for the hell of it
pApp->WriteProfileInt(_T("ArbitrarySectionName"), _T("engrAge"), age);

// not using pointer anymore
pApp = NULL;

To get information from the registry, you would have needed to save information there in the first place. If there is nothing there, you would get blank information. To get the information from the registry you would use the following code to get it:

// get the current application object
CWinApp* pApp = AfxGetApp();

// get string from registry and assign to a string
// GetProfileString returns a CString object
// GetProfileInt returns an integer
// "ArbitrarySectionName" is where the collection of information is stored (you set this on save)
// "engrName" and "engrAge" are the variables in the section "ArbitrarySectionName" where you saved single pieces of data
CString strVar = pApp->GetProfileString(_T("ArbitrarySectionName"), _T("engrName") ) );
int intVar = pApp->GetProfileInt(_T("ArbitrarySectionName"), _T("engrAge") ) );

// not using pointer anymore
pApp = NULL;

You can use both pieces of code anywhere in your MFC classes. Just note there are only functions for integers and strings. None for decimal numbers, unfortunately. For more information, here are some links to MSDN:

SetRegistryKey()
WriteProfileInt()
GetProfileInt()
WriteProfileString()
GetProfileString()
Article that I used to figure out how to use the registry

Creating easy custom buttons in Android

Wouldn’t it be cool if you could make your own buttons? Well, I’ve done a bunch of hax here and there where I use ImageViews for buttons and switching the image on press and such, and sure, that works. But it isn’t as clean, and well coded as this implementation here.

What this is going to involve is putting an XML layout in your drawables folder. I know, you’re scared. I was too at first. But now, I’m creating custom buttons like its going out of style (which it probably is).

The essence here is we are going to take the style of the original Android button, and override its image resources with our own, while leaving the rest of the functionality alone. Lets start with putting the images for the button you want to use.  This example just uses an up and a down state.

Just right click and save as for these images.  Copy them into your drawables folder.

Now, the magic happens.  Create a new file in your drawables folder and call it “new_button.xml”

Paste the following code into this file

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_window_focused="false"
android:state_enabled="true"
android:drawable="@drawable/custom_button_up" />
<item
android:state_window_focused="false"
android:state_enabled="false"
android:drawable="@drawable/custom_button_up" />
<item
android:state_pressed="true"
android:drawable="@drawable/custom_button_down" />
<item
android:state_focused="true" android:state_enabled="true"
android:drawable="@drawable/custom_button_down" />
<item
android:state_enabled="true"
android:drawable="@drawable/custom_button_up" />
<item
android:state_focused="true"
android:drawable="@drawable/custom_button_up" />
<item
android:drawable="@drawable/custom_button_up" />
</selector>

Excellent. For now, we are just dealing with 2 states, pressed and unpressed. The variables you see above make it clear the different button states you could have if you wanted.

Now, we need to make a “styles.xml” file, this is where your program will look for styles that you have declared. Where do I put this styles.xml you wonder? In that folder you probably never use, the “values” folder. So, go to your values folder, and create a file called “styles.xml” and paste this code into it:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="NewButton.Button" parent="@android:style/Widget.Button">
<item name="android:background">@drawable/new_button</item>
</style>
</resources>

Excellent! Now you’re ready to use your custom buttons! In your main layout, or whereever you want to use this button, call this in the code

<Button
android:id="@+id/custombutton"
style="@style/NewButton.Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>

If all goes well, this is what it should look like!

If you just skimmed to the bottom looking for source code, youre in luck. Download below.  Helpful?

http://www.inphamous.com/code/examples/Custom_Buttons.zip

Somthing extra…

Try this-  Since its still a button, you can add text on top of this bad boy.  Keep that in mind when designing your own custom buttons.  Someday, I will enlighten you on how button images properly stretch using the 9 patch tool.  Heres the guide from google if you don’t want to wait for me

http://developer.android.com/guide/developing/tools/draw9patch.html

-inph

Android Simple Progress Dialog implementation

Add a progress dialog very simply into your code.


private ProgressDialog mDialog;
mDialog = new ProgressDialog(this); // This being a context, could try getBaseContext() as well

Then, say you want it to show up on a button press. In the buttons listener, put this in (you can adjust the variable numbers later after it works)


mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mDialog.setMessage("Gathering Wireless Data...");
mDialog.show();
mDialog.setProgress(0);
mDialog.setMax(60);

Then, if used in conjunction with the thread example from below, put this in when you want to increase the progress bar


mDialog.incrementProgressBy(1);

And then finally, when you want it to go away,


mDialog.dismiss();

ez

Implementing a thread in Android

Here is a simple way to implement a thread into your program.  I usually use it when I want to scan something every few seconds or something.  The onStart and onStop will start and kill your thread.  The sendEmptyMessage is what you use in the thread to update your UI.   All of these methods will go below your onCreate(Bundle whatever) function.

You don’t have to call anything in the onCreate function to make it run.  In this example it will start running when the program starts, however you could call startScan() where ever you want

@Override
public void onStart(){
    startScan();
    super.onStart();
}

@Override
public void onStop(){
    isRunning = false;
    super.onStop();
}

public void startScan() {
    new Thread() {
        public void run() {
            while (isRunning) {
                try{
                    Thread.sleep(2000); // How long the thread will wait in milliseconds.  Not 100% accurate

                    if(!isRunning) {
                    break;
                    }
                    // Do stuff here
                    hRefresh.sendEmptyMessage(REFRESH SCREEN);
                }catch(Exception e){
                }
            }
        }
    }.start();
}

// Refresh handler, necessary for updating the UI in a/the thread
Handler hRefresh = new Handler(){
    public void handleMessage(Message msg) {
        switch(msg.what){
        case REFRESH_SCREEN:
        //Do stuff in here that you want updated in the screen
        break;
        default:
        break;
        }
    }
};

Find this helpful? Know a better way of implementing a simple thread? Please feel free to share. Do you need this code uploaded into a sample project? If there is a demand I can start creating basic empty projects that illustrate the code in action. Enjoy!