Posts tagged ‘code’

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

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();
            }
        }