Posts tagged ‘sample’

iPhone sample code

I figured I would try out developing on Mac Os making an iPhone app. My first experience on the Hackintosh building an application ( my first blog post from it as well ). Anyway, I downloaded the SDK got xCode going and followed some Hello world tutorial. I feel Hello world is just too simple to get a feel for the environment and Objective-C. So I decided to port my HandiCap Android sample to the iPhone, should give me enough time to play with xCode and get a feel for it.

As I started up xCode and started coding first I noticed was the keyboard shortcuts which are strange when using PC keyboard on the Mac, I run the Mac in a VM. I understand I can map that anyway I want so that shouldn’t be a problem if I decide to do some more development. As I knew this sample was going to be short I didn’t bother changing it. When using xCode it doesn’t really feel like an IDE rather a collection of different tools. I had a hard time finding out how to set controls on a view in the beginning once I got the appropriate tools open it was pretty much straight forward. One thing that I don’t really understand is when you link controls to the File owner, why does that link your controls to your code view ? why not link that to the view itself as that is where the code resides ? I guess I will figure that out later as time goes on.

So let’s take a look at the code, first you need to reference the controls in the header file that you already setup in the Interface builder. Yes you need to do that by hand, it is not taken care of by the IDE, more integration is needed on the IDE’s behalf if you ask me. Note the UITextFieldDelegate tag on the controller, this one is needed to hide the keyboard when Return is pressed along with code in the class file.

#import <UIKit/UIKit.h>

@interface HandiCapViewController : UIViewController <UITextFieldDelegate>
{
       
        // First half
        IBOutlet UILabel *lbPlayer1;
        IBOutlet UITextField *txPlayer1;       
        IBOutlet UILabel *lbPlayer2;
        IBOutlet UITextField *txPlayer2;
       
        // Second half
        IBOutlet UILabel *lbWinPlayer1;
        IBOutlet UITextField *txWinPlayer1;
        IBOutlet UILabel *lbWinPlayer2;
        IBOutlet UITextField *txWinPlayer2;
}

(IBAction) btCalculate_Clicked:(id)sender;

@end

Then we start coding in the class ( .m ) file

#import "HandiCapViewController.h"
#include <tgmath.h>

@implementation HandiCapViewController

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
(void)viewDidLoad
{
    [super viewDidLoad];
       
        // Disable the two result fields
        txWinPlayer1.userInteractionEnabled = FALSE;
        txWinPlayer2.userInteractionEnabled = FALSE;
}

(void)didReceiveMemoryWarning {
        // Releases the view if it doesn’t have a superview.
    [super didReceiveMemoryWarning];
       
        // Release any cached data, images, etc that aren’t in use.
}

(void)viewDidUnload {
        // Release any retained subviews of the main view.
        // e.g. self.myOutlet = nil;
}

// Shut down the keyboard
(BOOL)textFieldShouldReturn:(UITextField *)textField
{
        NSLog( @“textFieldShouldReturn start”);
       
        // This code should be made dynamic instead of ugly if / else
        if( textField == txPlayer1 )
        {
                [txPlayer1 resignFirstResponder];
        }
        else if( textField == txPlayer2 )
        {
        [txPlayer2 resignFirstResponder];
        }

        return TRUE;
}

               
// Calculates handicap
(void) calculate:( double *) pdaPlayers;
{
        // STRONGER is lower handicap
        // See who is better rated coming in,
        Boolean bStrongerFirst =  pdaPlayers[0] < pdaPlayers[1];
        // Holds results
        double strong_race, weak_race;
       
        if( bStrongerFirst )
        {
                // What’s the race
                weak_race = MAX(2, 6floor( pdaPlayers[1] ));
                strong_race = weak_race + round( pdaPlayers[1] – pdaPlayers[0] );
                // set the slots before returning
                pdaPlayers[0] = strong_race;
                pdaPlayers[1] = weak_race;
        }
        else
        {
                // What’s the race
                weak_race = MAX(2, 6floor( pdaPlayers[0] ));
                strong_race = weak_race + round( pdaPlayers[0] – pdaPlayers[1] );
                //  Set the slots before returning
                pdaPlayers[0] = weak_race;
                pdaPlayers[1] = strong_race;
        }
}

(IBAction) btCalculate_Clicked:(id)sender
{
        NSLog( @“Button clicked start”);
       
        double dPlayerOne = [txPlayer1.text doubleValue];
        double dPlayerTwo = [txPlayer2.text doubleValue];

        // What is the race
        double players[2] = { dPlayerOne, dPlayerTwo };

        // call the function to calculate
        [ self calculate: players ];

        // Display it
        txWinPlayer1.text = [NSString stringWithFormat:@“%.0f”, players[0]];
        txWinPlayer2.text = [NSString stringWithFormat:@“%.0f”, players[1]];

        NSLog( @“Button clicked end”);
}

(void)dealloc
{
        // First half
        [lbPlayer1 release];
        [txPlayer1 release];
        [lbPlayer2 release];
        [txPlayer2 release];
       
        // Second half
        [lbWinPlayer1 release];
        [txWinPlayer1 release];
        [lbWinPlayer2 release];
        [txWinPlayer2 release];
   
        [super dealloc];
}

@end



I disabled the two result fields in code in the viewDidLoad function as it did not work to set Accessibility Enabled = false from the Interface builder, I don’t know why.
The textFieldShouldReturn function implements the functionality that goes with UITextFieldDelegate in the header file. Simply when the user is done with input in the two text fields he can hit return on the keyboard and the keyboard gets hidden again.
The calculate function is a straight port from the Android code, I only had to include tgmath.h and use the math functions from there.
The btCalculate_Clicked is where all the functionality happens, simply convert the text input from string to double then call calculate and display in the result fields. There is no error checking on the input as I was feeling lazy.
I’m using NSLog to log out to the console, if you want to create a program for production you should maybe write your own logging or use third party library to be able to control the logging level both debug and runtime.
Lastly we have dealloc function where we release the resources the code has been referencing. As pointed out by my friend Mick they are introducing automatic dellocations by the compiler called ARC ( Automatic Reference Counting ) in the near future. That should be welcomed by objective-c developers as they don’t have to keep track of and releasing resources, fewer bugs and more productivity. Some changes discussed on Stack Overflow This experience reminded me of other c / c++ coding with a twist I find the [ class function:param ] syntax strange, but I’m sure I can get used to that.


Below is the app in action and here is the code if anybody is interested HandiCap xCode project

Android GUI thread timer sample

I was looking for a simple Android timer to do updates on ticks in one of the views I’m playing with. The problem with spinning off another thread brings up two issues, one is that it takes more resources and the second one is that you will have to switch back over to the UI thread to update the screen. Then I came across a much better solution in the SDK documentation click here. I had to read it a couple of times and when I imported it into my app had to figure out some things a long the way. So for your benefit here is a cut down simple version.

In case you didn’t know see how easy it’s to use the built in Log class, the output will be visible in LogCat output. Also note the call Handler.removeCallbacks(mUpdateTimeTask); to free resources.

//
package us.kristjansson.test;
//
import us.kristjansson.test.R;
//
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Window;
//

public class FxFireWorks extends Activity
{
        // Timer
        private Handler mHandler = new Handler();
        //
        private Runnable mUpdateTimeTask = new Runnable()
        {
           public void run()
           {
               // Do something
               Log.d( this.toString(), “Do something !!”);
               // timer
               mHandler.postDelayed(mUpdateTimeTask, ( 2 * 1000)) ;
           }
        };
       
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        // Hide the title bar
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.fireworks);
   
        // timer
        mHandler.removeCallbacks(mUpdateTimeTask);
        mHandler.postDelayed(mUpdateTimeTask, 100);
    }

    @Override
    public void onStop()
    {
        super.onStop();
       
        // timer
        mHandler.removeCallbacks(mUpdateTimeTask);
    }
   
}

Android code sample

I wanted to try some smart phone development. I started with Mac OsX in a VirtualBox got the Os installed on the virtual machine, but it wouldn’t boot for me after install. As I was fiddling with that on my Windows box to do iPhone development I thought this is way harder than it’s supposed to be.

Then I thought let’s see how this compares to doing Android development. Went to the Android SDK site and got the SDK which integrates with Eclipse very easily. The installs are just a few clicks of a button and your all set. Of course they have a Hello world sample that you will have running in Android emulator in matter of minutes. The install instructions show how to setup different devices under the emulator etc.

Now what about something more than just Hello world, the SDK comes bundled with all kind of samples, both controls and graphics along with more elaborate Google maps location based samples. It has plenty of stuff to get you going. The great thing is that the code is plain old Java so if you have done any Java or C# development you will feel right at home.

I wanted to do something basic before going into any real development. My idea is to create a simple calculator to calculate handicap score. I used to play pool and we would have a simple handicap system that needed to be referenced to calculate the race between two people that have been matched up.

When Android project is created in Eclipse it will create a bunch of files, resources, manifest, etc. and the main Activity class. The Hello world sample creates control dynamically in code but that can be hard to maintain when your project increases in size. The way to do it is to declare the controls in a XML resource file and then reference it in code. I didn’t see a editor to handle the controls visually but I’m sure there are some out there.

For a simple app the XML is found under res/layout/main.xml in my case it will look like this.

<?xml version=“1.0” encoding=“utf-8”?>
<RelativeLayout xmlns:android=“http://schemas.android.com/apk/res/android”
    android:layout_width=“fill_parent”
    android:layout_height=“fill_parent”>

    <TextView
        android:id=“@+id/lbPlayer1”
        android:layout_width=“fill_parent”
        android:layout_height=“wrap_content”
        android:text=“Handicap Player1:”/>

    <EditText
        android:id=“@+id/txPlayer1”
        android:layout_width=“fill_parent”
        android:layout_height=“wrap_content”
        android:background=“@android:drawable/editbox_background”
        android:layout_below=“@id/lbPlayer1”/>

    <TextView
        android:id=“@+id/lbPlayer2”
        android:layout_width=“fill_parent”
        android:layout_height=“wrap_content”
        android:layout_below=“@id/txPlayer1”
        android:text=“Handicap Player2:”/>

    <EditText
        android:id=“@+id/txPlayer2”
        android:layout_width=“fill_parent”
        android:layout_height=“wrap_content”
        android:background=“@android:drawable/editbox_background”
        android:layout_below=“@id/lbPlayer2”/>

    <Button
        android:id=“@+id/btOk”
        android:layout_width=“wrap_content”
        android:layout_height=“wrap_content”
        android:layout_below=“@id/txPlayer2”
        android:layout_alignParentRight=“false”
        android:layout_marginLeft=“10dip”
        android:text=“Calculate” />

    <TextView
        android:id=“@+id/lbMustWin1”
        android:layout_width=“fill_parent”
        android:layout_height=“wrap_content”
        android:layout_below=“@id/btOk”
        android:text=“Number of games Player1 must win:”/>

    <EditText
        android:id=“@+id/txMustWin1”
        android:layout_width=“fill_parent”
        android:layout_height=“wrap_content”
        android:background=“@android:drawable/editbox_background”
        android:layout_below=“@id/lbMustWin1”/>

    <TextView
        android:id=“@+id/lbMustWin2”
        android:layout_width=“fill_parent”
        android:layout_height=“wrap_content”
        android:layout_below=“@id/txMustWin1”
        android:text=“Number of games Player2 must win:”/>

    <EditText
        android:id=“@+id/txMustWin2”
        android:layout_width=“fill_parent”
        android:layout_height=“wrap_content”
        android:background=“@android:drawable/editbox_background”
        android:layout_below=“@id/lbMustWin2”/>

       
</RelativeLayout>

Things to notice are the id’s of the controls they need to be unique and how the layout is done for each control you specify where it should show up relative to other controls. That way the manager rendering your view can order them and it will look pretty good.

As I mentioned before the code is in java.

//
package hello.world;
//
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;

public class helloActivity extends Activity implements OnClickListener
{

        /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        // The usual
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.main);
       
        // Wire up click event
        Button button = (Button)findViewById(R.id.btOk);
        button.setOnClickListener(this);
    }
   
   
    // Implement the OnClickListener callback
    public void onClick(View v)
    {
        // Input from user
        String sPlayer1 = ((EditText)this.findViewById( R.id.txPlayer1)).getText().toString().trim();
        String sPlayer2 = ((EditText)this.findViewById( R.id.txPlayer2)).getText().toString().trim();
       
        // Turn into doubles
        double[] players = {0,0};
        players[0] = Double.parseDouble( sPlayer1 );
        players[1] = Double.parseDouble( sPlayer2 );
       
        // Calculate
        calculate( players );
       
        // Set the results
        ((EditText)this.findViewById( R.id.txMustWin1 )).setText( “” + (int)players[0] );
        ((EditText)this.findViewById( R.id.txMustWin2 )).setText( “” + (int)players[1] );
    }
     
    // Calculates handicap
    private static void calculate( double[] pdaPlayers )
    {
        // STRONGER is lower handicap
        // See who is better rated coming in,
        boolean bStrongerFirst =  pdaPlayers[0] < pdaPlayers[1];
        // Holds results
        double strong_race, weak_race;

        if( bStrongerFirst )
        {
            // What’s the race
            weak_race = Math.max(2, 6Math.floor( pdaPlayers[1] ));
            strong_race = weak_race + Math.round( pdaPlayers[1] – pdaPlayers[0] );
            // set the slots before returning
            pdaPlayers[0] = strong_race;
            pdaPlayers[1] = weak_race;
        }
        else
        {
            // What’s the race
            weak_race = Math.max(2, 6Math.floor( pdaPlayers[0] ));
            strong_race = weak_race + Math.round( pdaPlayers[0] – pdaPlayers[1] );
            //  Set the slots before returning
            pdaPlayers[0] = weak_race;
            pdaPlayers[1] = strong_race;
        }
    }

}  // EOC
 

The onCreate function is the main function of the activity, to get button click event it will be setup there. The rest is straight forward and activated when the user clicks the button. The controls are addressed by R.id.xxxx which is the resource id’s given to each control in the layout XML. The R mapping is created when the project is compiled. For this simple sample, the user input is retrieved and used to calculate handicap which is then presented back to the user in controls below.

The app running in Android emulator
androidhandicap1

Update
—–
I just didn’t find the visual editor, it’s there in Eclipse it shows as tab when you open up the xml file. It’s very primitive one might be better off to use DroidDraw

C# Base32

I had the need to use Base32 at work some time ago to compress numbers. I had forgotten about it until today when I ran across some old code. As I was researching implementation for a developer on another system we interact with. The problem at the time was that we had numbers that are too big to fit in the field where we needed to write it. In order to do so we needed to compress it and we choose Base32 for the task.

Simply put, you take a number and you convert it to the 32 characters in the convert table, for example.

123456789 becomes VITXVD

Of course when you have the Base32 encoded number you can decode it back to the original number. If you couldn’t do that it wouldn’t be very useful.

VITXVD becomes 123456789

The RFC 4648 Base 32 alphabet
Value Symbol Value Symbol Value Symbol Value Symbol
0 A 9 J 18 S 27 3
1 B 10 K 19 T 28 4
2 C 11 L 20 U 29 5
3 D 12 M 21 V 30 6
4 E 13 N 22 W 31 7
5 F 14 O 23 X
6 G 15 P 24 Y
7 H 16 Q 25 Z
8 I 17 R 26 2



Note that one and zero are not used so there is no confusion between them O and I. When shuffling data between different systems, legacy etc they might not be interpreted correctly. You can create the Base32 encoding in different ways. Therefor if your interacting with another system exchanging data that system needs to use the same encoding / decoding as your system.

Below is a C# sample Base32 code.

class CxBase32
    {
        //
        private const string BASE_32_ALPHABET = “ABCDEFGHIJKLMNOPQRSTUVWXYZ234567”;
        private static int BASE_LENGTH = BASE_32_ALPHABET.Length;
 
        // Encode number to base 32 string
        public static string toBase32( int piNumToCode )
        {
            StringBuilder sRet = new StringBuilder();
 
            // loop until nothing left
            do
            {
                // Set the encoded character using mod
                sRet.Append(BASE_32_ALPHABET[piNumToCode % BASE_LENGTH]);
                // Adjust the reminder
                piNumToCode = piNumToCode / BASE_LENGTH;
            }
            while (piNumToCode != 0);
 
            return sRet.ToString();
        }
 
 
        // Decode base 32 string to a number
        public static int fromBase32(string psCodedString)
        {
            int iRet = 0;
 
            // Decode the alphabet
            for (int i = psCodedString.Length1; i > –1; i–)
                { iRet = (iRet * BASE_LENGTH) + BASE_32_ALPHABET.IndexOf(psCodedString[i]); }
 
            return iRet;
        }
 
    }  // EOC
 

And unittests

[Test]
        // Make sure encoded number can be decoded correctly
        public void randomBase32Test()
        {
            // Try some random number
            string encoded = CxBase32.toBase32(123456789);
            Assert.AreEqual(“VITXVD”, encoded);
            int decode = CxBase32.fromBase32( encoded );
            Assert.AreEqual(123456789, decode);
           
            // Another number just for fun
            encoded = CxBase32.toBase32(987654321);
            Assert.AreEqual(“RF24N5”, encoded);
            decode = CxBase32.fromBase32(encoded);
            Assert.AreEqual(987654321, decode);
        }
       
        [Test]
        // Make sure zero will return a value
        public void zeroBase32Test()
        {
            // Zero test, should return a value as well
            string encoded = CxBase32.toBase32(0);
            Assert.AreEqual(“A”, encoded);
            int decode = CxBase32.fromBase32(encoded);
            Assert.AreEqual(0, decode);
        }

MySql in C#

First download the Mysql ODBC driver from the download page.

Then download the .net connector, at this writing it was Mysql Connector/Net 5.2

You can choose to download only the binaries, extract and add /bin/MySql.Data.dll to your project. A help file for the classes is found at /Docs/MySql.Data.chm of the download.

With the dll added to the project, it’s very simple to connect to a MySql database as the snippet below.

using MySql.Data.MySqlClient;

namespace test
{
    class testit
    {
        private MySqlConnection mConn = null;
        private const string msConnStr = “SERVER=myserv.com” +
            “;DATABASE=somedbase;UID=theuser;PWD=thepassword”;

        public void test()
        {
            try
            {
                // Setup and open acceess to the database
                mConn = new MySqlConnection(msConnStr);
                mConn.Open();
                // simple count select
                MySqlCommand command = new MySqlCommand(“select count(*) from cars”, mConn);
                long ret = (long)command.ExecuteScalar();
                // how many rows in the table
                Console.WriteLine(“cars count=” + ret );
            }
            catch (Exception ex)
            {
                Console.WriteLine(“err=” + ex);
            }
            finally
            {
                if( mConn != null ) mConn.Close();
            }
        }