Category Archives: Java

Java language related programming, specifically as it relates to communicating with and utilizing .NET objects.

Drawing with the Canvas object in Android

When writing an Android game one of the first things I had to start looking at is the methods provided for drawing. Being that I had no real purpose for developing a 3D game, I decided to go 2D. There are many things that a bitmap can do for you in regards to saving you development time, but the game platform that I am pursuing next did much better with mathematical drawing.

This brought me to searching out the object that I would use to display colorful shapes that I chose at specific window positions. The first object I have come across to do this is the Canvas. A Canvas can be accessed by overriding the OnDraw method of the Android View object. A View is an object that you place in your layout to indicate UI functionality. While there are many methods in the Canvas that work well for drawing, I focused in on two of them which were drawLine and drawRectangle.

In my example I went through a few iterations to figure out screen width and what I should do with it, but ultimately I started focusing in on using a percentage of the screen with as opposed to using hard coded numbers, as it scales better on landscape mode if you go back and forth between portrait. Ultimately I came up with a method that looks like this to draw a block on my game:

GamePieceBlock block = m_BoardBlocks.get(i);
blockLeftSide = leftSide + (width / m_PiecesWide) * block.getXPosition();
blockRightSide = blockLeftSide + (width / m_PiecesWide);
Paint pnt = new Paint();

blockBottomSide = bottomSide - (height / m_PiecesTall) * block.getYPosition();
blockTopSide = blockBottomSide - (height / m_PiecesTall);

m_Canvas.drawRect(blockLeftSide, blockTopSide, blockRightSide, blockBottomSide, pnt);

This method draws a solid block of color at the position that I calculated.  To get the m_Canvas instance I set it in my onDraw method and then call down to my game methods to draw the object on the canvas.  The other method that I use is the drawLine method which looks like this:

m_Canvas.drawLine(rightSide, bottomSide, rightSide, topSide, boardPaint);
m_Canvas.drawLine(rightSide + 1, bottomSide, rightSide + 1, topSide, boardPaint);

HOW TO: Use Facebook Registration In .NET

As we all know Facebook is too big of a monster to not consider when developing our web applications.  Time and time again I have received the request to add a Facebook registration process to a store or blog that allows users to “Connect With Facebook” and remember their settings.  Luckily, Facebook has begun alpha support of a C# library which lets us have some fun with JSON.  Facebook uses a signed response method which encrypts information passed back and forth using your application secret and ID.  Here is some sample code for a page that would call to the Facebook API for registration/logging in.


<iframe src="

When using this approach Facebook will pass you back to the page you specify in the redirect_url with a Form field setup called signed_request.  The nice thing about this is you create a page that accepts this call back and handles the Form field appropriate to login or register a user.  The C# library that Facebook has started working on exposes some methods which allow you to interpret this response and get some data. Here is an example on how to retrieve the response and fetch some fields from it:


Imports Newtonsoft.Json.Linq
Partial Class FacebookRegistrationPageHandler
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        Dim fbaFacebookApp As New Facebook.FacebookApp
        Dim fsrSignedRequest As Facebook.FacebookSignedRequest
        Dim jobJSONObject As JObject

        fbaFacebookApp.AppId = "xxxx"
        fbaFacebookApp.AppSecret = "xxxx"
        fsrSignedRequest = fbaFacebookApp.SignedRequest

        jobJSONObject = JObject.Parse(fsrSignedRequest.Dictionary("registration"))
        Dim strReturnedName = CType(jobJSONObject("name"), Newtonsoft.Json.Linq.JValue).Value

    End Sub
End Class


using Newtonsoft.Json.Linq;
// ...
class FacebookRegistrationPageHandler : System.Web.UI.Page {

    protected void Page_Load(object sender, EventArgs e) {
        Facebook.FacebookApp fbaFacebookApp = new Facebook.FacebookApp();
        Facebook.FacebookSignedRequest fsrSignedRequest;
        JObject jobJSONObject;
        fbaFacebookApp.AppId = "xxxx";
        fbaFacebookApp.AppSecret = "xxxx";
        fsrSignedRequest = fbaFacebookApp.SignedRequest;
        jobJSONObject = JObject.Parse(fsrSignedRequest.Dictionary("registration"));
        object strReturnedName = ((Newtonsoft.Json.Linq.JValue)(jobJSONObject["name"])).Value;

HOW TO: Get A Date From A DatePicker

If you are writing an Android application, you likely have come across some form of the DatePicker object. This object exposes a UI that allows a phone user to pick a month, day and year. Unfortunately, the object itself does not expose any methods to turn this into a date object. Unlike similar controls across other languages, you must construct the date object yourself. While this does cause burden, you can also create your own DatePicker class and implement this method if you prefer. To do this, you can create the following method to return back a date object:

public Date getDate() {
    	return new Date(this.getYear() + 1900, this.getMonth(), this.getDayOfMonth());

Otherwise, you will have to create a new date object every time you want to fetch this information from the DatePicker. Cheers!

HOW TO: Connect To MS SQL Using Java

In an effort to support the multi-platform movement, Microsoft has a set of tools available for Java developers to allow seemless integration to SQL Server. If you are interested, you can download this tool set here. The advantage of using a Microsoft native driver as opposed to writing one of your own or using a third party driver is the awesome support that Microsoft provides for future updates etc.  Let’s take a look at how you might use this driver in your code.

For your first pass at connecting to SQL server, you may want to check if your server is IPv6 or IPv4. If it is IPv6, you will need the following line of code to make sure your connections are successful.

System.setProperty("", "true");

Next we will need to build our connection string. A good template that I use is simple for all kinds of setup, and allows for integrated security etc.

Connect to the default database on the local computer by using integrated authentication:

Connect to a named database on a remote server:

Connect on the default port to the remote server:

Connect by specifying a customized application name:

If you need more advanced options, you can find other properties that can be set in the connection string here. Finally, let’s create a connection for use in querying the database. The typical object to use is called the DriverManager.

String strURL = "jdbc:sqlserver://localhost;database=AW;integratedSecurity=true;";
Connection con = DriverManager.getConnection(connectionUrl);

Most importantly, I’m sure you will want to know how to query data. This can be done through simple selects similar to coding in a .NET language. Below is an example of a select statement with parameters. For more information about using the JDBC driver for various SQL tasks, check here.

public static void executeStatement(Connection con) {
   try {
      String SQL = "SELECT LastName, FirstName FROM Person.Contact WHERE LastName = ?";
      PreparedStatement pstmt = con.prepareStatement(SQL);
      pstmt.setString(1, "Smith");
      ResultSet rs = pstmt.executeQuery();
      while ( {
          System.out.println(rs.getString("LastName") + ", " + rs.getString("FirstName"));
   catch (Exception e) {

Grabbing Click Events In Droid App

Hello everyone,

Over the past few weeks I have stepped into the deep end of a market that I felt was up and coming. I decided to write a droid application fresh as a java guy, because I got my new Droid 3. First off, if you have a droid you know why I did this and if you don’t have it, go try one, they are awesome! To start, I had to get thrown into a world of XML oriented UI design which I realized how much I loved from XAML. I ran through a few droid tutorials on the developer site for droid and got myself setup with Eclipse and the droid addins.

My first application, I created a simple timer that had a progress button and updated a progress bar. The idea here was to recreate a classic Progress Quest application that you may or may not know. The nice thing that I found about this whole process was how open the community was and how easy it was to pick up a lot of the concepts. Here is some sample code below that I came up with for getting a hold onto a button click event and some multi threading in Java.

public class DroidQuestActivity extends Activity implements OnClickListener {
    private ToggleButton mApplicationToggleButton;
     /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
    public void setupFormVariables() {
       mApplicationToggleButton = (ToggleButton)findViewById(;
       mApplicationToggleButton.setOnClickListener(this);    }
    public void onClick(View v) {
       // Do some click events from the button