Archive for the ‘Android’ Category

Below are two applications that do exactly the same thing, but one was a whole lot easier to create. Can you guess which one? As an end-user it’s impossible to tell but in this article we examine how similar and yet different the development experience is for each of the apps. One of the apps below (on the right) is coded inAndroid 2.2 (aka Froyo) and the other using Windows Phone 7 Beta SDK. I tried to keep both projects as simple as possible so that people can understand the fundamentals over the design.

Download Sample Project Code Files

To get started with Windows Phone 7: http://developer.windowsphone.com, download the necessary software and Windows Phone SDK from the link listed. These tools will be used to run the examples; namely Visual Studio 2010, Windows Phone 7 Beta SDK, and Microsoft Expression Blend (optional).

The sample provided is just a small application which can convert between Fahrenheit, Celsius, and Kelvin.

I want to begin by addressing the similarities between the Android and Windows Phone 7 platforms. Both platforms have adopted the approach to separate design from logic. In Android, developers are used to coding “Layouts” and in Windows Phone 7 the equivalent is called a “Page”. Both of these layout methodologies involve creating an XML based layout. WP7 uses a mutated version of XML called XAML (pronounced “Zamel”). In both the Layouts and the Pages of each platform there is code behind that connects to your layout.

main.xml (Android)
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout android:id="@+id/widget0"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
</AbsoluteLayout>
MainPage.xaml (WP7)
<phone:PhoneApplicationPage
    x:Class="TemperatureConverterSample.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    shell:SystemTray.IsVisible="True">
    <!--LayoutRoot contains the root grid where all other page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
         
    </Grid>
</phone:PhoneApplicationPage>

The equivalent of an Android “Activity” would be best described by the C# class which is connected to your XAML page and extends Microsoft.Phone.Controls.PhoneApplicationPage.

Android Activity
public class MainActivity extends Activity {
        // Code behind goes here…
 }
WP7 Page
 public partial class MainPage : PhoneApplicationPage
 {
       // Code behind goes here…
 }

Okay so its clear that there are similarities in terms of the core fundamentals of each platform, not to mention Java and C# are like brothers from another mother.

Phone Controls

The Windows Phone 7 equivalent to Android Widgets are called Controls and are a part of the System.Windows.Controls namespace. These “UIElements” are used in much of the same way that Widgets are. For instance the “Convert” button used in the apps is defined as such in  Android and WP7 respectively:

Android
<Button
android:id="@+id/calculateButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Convert"
android:layout_x="106px"
android:layout_y="292px"
>
</Button>
WP7
 <Button Content="Convert" Height="83" HorizontalAlignment="Left" Margin="24,487,0,0" Name="calculateButton" VerticalAlignment="Top" Width="400" Click="calculateButton_Click" />

Listeners vs Events

To handle a Button click in Windows Phone 7 we would use a Click Event rather than an Android Event Listener.

Android Click Listener
this.closeButton = (Button)this.findViewById(R.id.calculateButton);
        this.closeButton.setOnClickListener(new OnClickListener() {
          @Override
          public void onClick(View v) {
     }
}
WP7 Button Click Event
Xaml Event name specified
<Button Content="Convert" Height="83" HorizontalAlignment="Left" Margin="24,487,0,0" Name="calculateButton" VerticalAlignment="Top" Width="400" Click="calculateButton_Click" />
C# Event Method Definition
private void calculateButton_Click(object sender, RoutedEventArgs e) {
      // Code for button
}

The Layout of your Apps

Similar to Androids Layout Views, Windows Phone 7 supplies developers a set of objects to layout Controls. There are Grids, StackPanels, Canvas and so on which have various methodologies of displaying UIElements. You can write your own as well. The reference for all of these such layouts can be found on the Microsoft MSDN reference pages.

hello-linearlayout

The equivalent for a LinearLayout in Android would be the StackPanel in WP7.

Differences Between the Platforms

So far we have yet to discuss the differences between the platforms. The main difference between Android and WP7 is in the development tools. In terms of coding, Android may be built on Java which is an open source platform with a ton of available code but C# is a very strong programming language with many nice features of its own. For instance, data binding to Controls in Silverlight is a really nice standard feature. After coding your app you can style it up in Microsoft Expression Blend 4. User interface designs can be “templated” which provides a CSS stylesheet type logic for programming your user interfaces on the phone.

Behaviors in Microsoft Expression Blend 4 allow people to build games use physics like a physics engine without even doing any code. Any Control in Silverlight can have a custom style. For instance, you can have a button which fades out or changes to all the colors of the rainbow when clicked. Whatever your imagination can think up is possible in an easy and highly customizable fashion.

Conclusion

The Android Platform and Windows Phone 7 share a lot of commonalities. It will take a while to get used to migrating from Android + Eclipse to Windows Phone 7 + Microsoft Visual Studio + Expression Blend but in the end it is a much smoother development experience. The tools which Microsoft provide add a wealth of ease to the lives of us developers.

Source: The Dirty Developer

Advertisements

10x0729iub23532aas

A wordy headline, to be sure, but a pleasing one nonetheless. We came across HTC’s Chinese web portal listing the Desire as coming with Android 2.2 (with Sense!) and simply had to ping the official source for confirmation. It turns out the info up there is no mistake: all HTC Android handsets shipping to China — which includes the Wildfire and Tianyi — will do so with Froyo preloaded, cutting down on your upgrade angst at least until the Gingerbread man comes a’knocking. HTC has also reiterated that a 2.2 update for its phones already on the market will be delivered “very soon,” so if all goes all, we should be looking at a Froyo-dominated August in the land of High Tech Computers.

Source: Engadget

Part–2 Graphical Elements

Posted: July 28, 2010 in Android, Development

android_apps

In this tutorial, we will be continuing from where we left off with the “hello world” application.  This time adding a graphical user interface (GUI) and a “toast”. The GUI will consist of a button, textbox and a label. The “toast” will be issued onto the screen when the button is pressed.

Some may wonder what a toast is.  Well, for non-programmers, a toast is a text notification that for the most part is used only to display an error on the screen (I am a big fan of using toasts instead of an alert on the screen as its less intrusive).  For this article we will use a toast to display a message on the screen that will take the text in the textbox and issue a “Hello Greg” onto the bottom of the screen.  After this article completed you will be able to successfully make toast commands, design the layout of the hello world program, and pull text from a textbox.

We are going to start off by copy our existing Hello World project so that we can use the original in every way but have two separate projects to show the difference and both can be used as references.  To do this we will right click on the root of our HelloWorld project in the right hand pane (Navigation Explorer), navigate to copy (not Copy Qualified Name) and click it.  Then find a blank space in the Navigation Explorer, right click again and click paste.  You will be asked to supply a new name for this project and whether to use the default location.  We will name the new project ImprovedHelloWorld and we will leave the checkbox checked that says “use default location”.  Press OK and the new project will be generated from the old one.

Image-1

The first thing we are going to accomplish is changing the strings.xml file to add another node under app_name.  We will do this by copying the node above it and pasting the copied material directly under the last </string> element.  Then we will change the name of the string to press and in between we will write Press Me!.  Next we will alter the hello node and change the text to say Enter Your Name Here: instead of Hello Android, Hello World!. This being accomplished we now need to design the GUI (Graphical User Interface).

Image-2

To do this navigate to main.xml and we are going to go over what everything does up to this point.  We first off have a node called LinearLayout which essentially creates a space for adding objects such as textboxes, buttons and the like and will format the layout for us.  So LinearLayout will organize one thing right after the other in a one column and one row type of deal.  Next we have a TextView which in any other label we could call a label.  Now to go over what all of the parameters are in the nodes we just mentioned.  android:layout_width & android:layout_height are used to determine what will happen to an object when it is used within a layout.  There are two options when using this and they are fill_parent or wrap_contentfill_parent will do exactly as it states, it will size the object so that it will fill the screen either vertically or horizontally.  wrap_content will format the object to expand or shrink to the size of the content displayed within.  Both of these variables can be used in many different objects including but not limited to Layouts, Text Views, Text Boxes, and Buttons.  android:text is used in certain objects like TextViews and TextBoxes to display text to the user.  As of right now, we are presenting the user with text but calling it from strings.xml instead of entering the text right in the node itself.  To reference strings.xmlall that is needed is to put @string/press, where press is the name of your variable, inside the quotations.

Now that we are familiar with the terms, we will need to modify this to first house a label, textbox and finally a button.  To do this we will simply add a textbox and button since we already took care of the label in the string.xml.  To add a Textbox we will start on a new line under ending of the <TextView /> node.  Just to be clear I will add code inline and explain why we are adding it afterwards. <EditText android:id=”@+id/helloName” android:layout_width=”fill_parent” android:layout_height=”wrap_content” />.  EditText will be our textbox in this instance.  Also when giving items an ID it is best to follow these practises of adding@+id/ before your variable name which makes it possible to tie into your .java file later.  Next we will add <Button android:id=”@+id/go” android:layout_width=”fill_parent” android:layout_height=”wrap_content” android:text=”@string/press” /> directly underneath the ending of our EditText node.  Notice we are referencing the string.xmland calling the node that says Press Me! which will appear on our button now.  If you were to run this project now you would be able to see the layout of the program we just made but we are unable to get it to do anything except enter text in the textbox.

This next section will contain a lot of code and I will provide most of the screenshots of the code to help you through.  First, it is good to realize every time you would like to reference an object in your layout we need to import it.  We will need to add imports for our button and textbox.  We can do that bu adding these lines of code to the imports section at the top:

1 import android.widget.Button;

2 import android.widget.EditText;


After that we will need to include four more imports, the first being for event listen to add to our button, the second will be for the toast that we will call when the event handler runs, the third being the context of the application and the fourth to get the view of the application and handle the layout and interaction.  These imports can be added under the previous ones and will look like this:

1 import android.view.View.OnClickListener;

2 import android.widget.Toast;

3 import android.content.Context;

4 import android.view.View;


After these are added to your imports we are ready to get into coding the event handler for our button and the onCreate functions, which is called when the program is started.  To make things easier and to complement the screenshot, I will post the rest of the code and explain what the important lines are doing and why we are using them.

1 public class HelloMain extends Activity {

2 EditText helloName;


We are creating a reference to our textbox above any function so that it only has to be declared once but instantiated many times if need be.

01 /** Called when the activity is first created. */

02 @Override

03 public void onCreate(Bundle savedInstanceState)

04 {

05 super.onCreate(savedInstanceState);

06 setContentView(R.layout.main);

07 // Capture our button from layout

08 Button button = (Button)findViewById(R.id.go);

09 // Register the onClick listener with the implementation above

10 button.setOnClickListener(mAddListener);

11 }

Above we capture the button from the layout using a variable.  With this variable we are going to assign it an onClick Event Handler as shown on the last line above.  Below we are creating the Event Handler for it to be hooked in above.  After creating this function it will be able to pull the text from the TextBox and display it with static text.

01 // Create an anonymous implementation of OnClickListener

02 private OnClickListener mAddListener = new OnClickListener()

03 {

04 public void onClick(View v)

05 {

06 long id = 0;

07 // do something when the button is clicked

08 try

09 {

10 helloName = (EditText)findViewById(R.id.helloName);

Here we instantiate the TextBox we declared earlier and capture the Textbox in the layout by finding it by the ID that we gave it.

1 Context context = getApplicationContext();

2 CharSequence text = "Hello " + helloName.getText() + "!";

3 int duration = Toast.LENGTH_LONG;

4 Toast toast = Toast.makeText(context, text, duration);

5 toast.show();

The above code will take Context (the facet to our applications enviroment) and and add it to our Toast along with our dynamic CharSequence text and the length the Toast will appear onscreen, which in this case we want it to be longer.  It is key to note how to make a Toast as it is more efficient that popping up textboxes to the user as well as it is less distracting.

01 }

02 catch (Exception ex)

03 {

04 Context context = getApplicationContext();

05 CharSequence text = ex.toString() + "ID = " + id;

06 int duration = Toast.LENGTH_LONG;

07 Toast toast = Toast.makeText(context, text, duration);

08 toast.show();

09 }

10 }

11 };

12 }

The last thing we are doing for this function is putting all the important stuff mentioned above into a try catch statement which will try our important code and if there is an error it will display a Toast letting us know there was an error and a message about that error.  For functions such as these is it crucial to have precautions in place to catch errors and not have a program force close.  It is important to put the user first in thinking about UI and any error messages that might occur.  If an error somehow sneaks into your program try catch statements will catch the error and make it “cute and fuzzy” for the user.

Top half of code:

Image-3

Bottom half of code, elapsed by previous view of code:

Image-4

After we have coded the main content for our .java file, we can now proceed to run the application and view our completed Improved Hello World program.  Notice that when you press the button and your textbox has not text in it that the program will still function correctly.  This is a good feature to have so that you don’t start seeing Toasts containing error messages.  The completed product should look like this when the button is pressed:

Image-5

This would conclude our Improved Hello World example but the learning is far from over.  Next post we will examine Databases and a look into some simple queries as well as building a database from the ground up.  As always, if you have any problems with coding this article, feel free to leave a comment and I will assist in any way possible! If you can’t wait for the next post you can read up on databases before the next posting.

Part–1 Hello World

Posted: July 27, 2010 in Android, Development

Android Bots

This article will focus on developing a simple hello world program for android using Java. Google has recently released a “cute and fuzzy” programming environment for beginners to get into but I haven’t had the chance to try it, so we will be focusing on the Eclipse IDE here, which you should have set up in the last post.  When creating a text based project there are two very important items.  It will involve creating an android project, going through the necessary steps to complete both the (1) XML files and the (2) Java file and get this project ready for production and eventually deployment.  The requirements of this project are simple, know the basis of XML (for new comers if you don’t that’s OK too, you will learn) and know Java (very basic knowledge but you will learn as we go and we will modify a few parts of the java file today).

Eclipse

Start by firing up Eclipse and clicking File, New then Project. We are going to navigate to Android folder and select Android Project and click next. If you have updated your Android SDK correctly, your next screen will look like this. This screen requires we enter all data correctly including Project Name, Build Target, Application Name, Package Name, Create Activity, and Min SDK Version. These are important terms to know because they will control what keywords you can access and what your project looks like when you first create it. So to summarize:

  • Project Name: Will be the name you would like to use for your new project. In this instance we will use “HelloWorld” (I am a programmer and loath spaces you might choose to have them but it shouldn’t make a difference)

  • Build Target: This will specify what API you will be utilizing in your projects. It is key to choose wisely or you may lose out on a wider audience than anticipated. It is always best to think of what your program will use and see if a lower build will support those functions before cornering yourself with a higher API. For this program we are going to choose Android 1.5
  • Application Name: Will be the name you choose for your Application to be called. This can be changed later on and for right now we make that field equal Hello World.
  • Package name: The package name will consist of your company’s standard package name that you would use or in my case I use my entrepreneurial one. For this I am entering in com.gregrjacobs.helloworld but you can enter in anything you wish. Also, make sure it is in all lower case for good coding practices.
  • Create Activity: You will want to make sure that the box is checked before Create Activity because this option will do most of the work you just have to give it a name. NOTE: do not call this “Activity” as your project will cease to function and you have to go through the pain of making it all over again or manually correcting it. I am going to use HelloMain as my activity name, again use what you wish though.
  • Min SDK Version: This will have to be a number you enter denoting the platform you would like to target and if this application will show up in the marketplace of certain devices. If you look to the build target devices after platform tab on Android 1.5 you will see the number 3 and that will be our minimum SDK Version. Once everything is filled out press Finish.

Image-1
This will create the core of our project ranging from the Android 1.5 JAR file to our Java and XML files. The most important things right now are the files in the src/com.gregjacobs.helloworld/ folder and the files in the res/ folder. First we will look at the main.xml which is located in res/layout/. This file will hold the layout of your application including textboxes, labels, dateTimePickers and the like. In the main.xmlwe will see that we are using a LinearLayout which will organize items into a single row or column. This can be handy sometimes (other times not so much) and for this example it will work, so leave it like this because we will be displaying text so it makes no difference. Next is the strings.xml file which will conveniently house
all of strings in the application. This is especially useful to keep the clutter out of your Java and main.xml file. We are actually going to change the string called “hello” fromHello World, HelloMain! to Hello Android, Hello World! And our string namedapp_name can stay how it is.

Image-2

After doing this we are going to navigate to the package name we created and openHelloMain.java and this will contain the code to run the XML files we were just looking at. The first line will contain our package name that the java file is associated with. Next, in the picture above, we have imported the OS bundle and the activity function that will run our app. Later on when we explore adding textboxes and labels we will be importing widgets into our files and we will put the imports just under these two shown above. Next is our class that basically says when the application starts up, set the view of the screen to the layout labeled main. This is interesting in the sense that you can design many different layouts depending on the state you application is in. Of course with a hello world program we only need this one layout but the option is there for you to experiment with.

When we are done tweaking everything we wanted, we are going to build the application and run it on the emulator we created last post. To do this we go to the top of the eclipse screen and navigate to the button that looks like this and press it. This will prompt you to say what type of project you would like to run. We want to run an Android Application and press ok.
The emulator should pop up onto your screen and load up. The first load time of your emulator will be atrocious but after that you should have no problems with load. When the emulator is done loading it may ask you to press Menu to unlock, do so by pressing menu just under the screen. You don’t have to navigate to load your project it will do it by itself it just has to load the rest of the software and you should end up with a result like this:

Image-3

When working with tools like the eclipse IDE and AndroidSDK, making simple text based programs is a breeze. The next post coming to this series will get somewhat more difficult by developing an improved Hello World program. If anyone had any problems with this today make sure to leave a comment and I will try to get back to you before the next post. If you can’t wait to look ahead to designing an interface for your android application or looking into databases, these are the places to go; Data Storage and User Interface. Until next post, happy hacking.