Pages

Monday 15 October 2012

How to Start Developing for Windows Phone, Android or iOS

An increasing number of first-time mobile app developers are also first-time developers. This makes sense if you think about it; mobile is the hot new platform and the barrier to entry is a lot lower for mobile devices.
Furthermore, a simple — yet well-done — mobile app can be functional and a big success; look at the prevalence of tip calculators, flashlights and other applications. It’s much harder to find that sort of success with a small, single-purpose desktop app.
Although the barrier to entry is lower for mobile app development, you still need to be prepared to learn. If you have no previous experience in programming for the web or in a language like C, Java or C#, grasping the basics is going to take more time. Thus, we’ve traversed the web, the bookstore and bugged our developer friends to find some of the best resources — online and off — for the beginning mobile app developer.
There are development platforms that can make it easier for web developers to transition to mobile platforms, but we also think it pays off to invest time in actually learning the programming languages for your mobile platform of choice. On iOS, this means learning Objective-C and also learning Cocoa Touch. Android programming is very similar to Java, but with Android-specific APIs and frameworks. Microsoft’s Windows Phone uses Silverlight, which means if you have experience with C# or .NET, you should find yourself at home.

Windows Phone Apps

 
Windows Phone 7 just launched in Europe and Asia and will be in the U.S. on November 8. This platform is brand new and already shows a lot of promise.
Perhaps more than any other software company, Microsoft excels at providing developers and would-be developers with tons and tons of resources and development tools. Unintentionally hilarious or not, Steve Ballmer’s famous “Developers, Developers, Developers” speech wasn’t that far-off.
Windows Phone 7 is just in its infancy and the development tools are still being modified and adjusted. Because of this, we would actually suggest that first-time programmers wait a few months before jumping into Windows Phone 7. However, if you have C#, .NET, Silverlight or WPF experience, building apps for Windows Phone 7 is going to be a very easy transition.
Here are some places you can go to get more information of Windows Phone 7 development:
  • App Hub — The App Hub is Microsoft’s portal for Windows Phone and Xbox 360 developers. It provides access to tools, forums and blog entries and documentation from the experts.
  • Getting Started with Windows Phone — This page contains links to hands-on labs and videos about how to get started developing for Windows Phone 7.
  • Silverlight for Windows Phone — This portal offers lessons and training on using Silverlight to build Windows Phone 7 apps.
  • XNA Framework 4.0 for Windows Phone — This training course contains lessons and videos for using the XNA Framework to build games for Windows Phone 7.

Note: Developing for Windows Phone 7 requires Windows.

Android App Development

 



As you would expect, Google’s Android Developers portal has tons of useful information, guides and tools. The SDK, emulators and development tools are all accessible for free, and there are tons of examples and tutorials on the site.
Android’s selection of print or e-books isn’t as complete as what is available for the iPhone — and you need to be sure that the book you look at is focused on Android 2.0 or above. Still, if you look at the number of books projected for publication into next year, you can see this is an area that is on the move, big time.
Here are a few recommendations:
Some of the best Android stuff is available online; here are some sites to keep in your bookmarks:
  • XDA Developers — XDA Developers is a great resource for fans of modding their Android phones or installing custom ROMs, but its forums are also a great place to get answers to questions and learn.
  • Anddev.org — This forum is for Android development and Android tutorials.
  • Android Developers Community Portal — This is part of Google’s official Android Developers page, but it’s a good guide to the various mailing lists and Google Groups for Android development.
 

iOS App Development, Books, Sites and Resources

 
 
learning the basics of iOS programming, the Apple Developer site is chock-full of great information. Registration for access to developer documents is free, though you have to pay to become an iOS developer ($99 a year) to get access to extended tutorials, videos from WWDC and other tools. There are also literally dozens upon dozens of books about developing for the iPhone. I’m a big fan of technical book resources, but keep in mind that because of how quickly mobile platforms evolve, it isn’t uncommon for information to be out of date — or less up-to-date — upon publication.
Still, some of my picks for really great iOS/Objective-C/Cocoa/Cocoa Touch education include:
  • iPhone App Development: The Missing Manual — This book by the Iconfactory’s Craig Hockenberry is a really great guide to the ins and outs of iPhone development.
  • iPhone Programming: The Big Nerd Ranch Guide — If you have the money and can take a week or two off of work for some hands-on education from some of the best instructors around, you should seriously check out The Big Nerd Ranch. If you don’t have that kind of time, then you take a look at the book version by Aaron Hillegass and Joe Conway. Hillegass is also the author of the seminal Cocoa Programming for Mac OS X, now in its third edition.
  • iOS Developer’s Cookbook — My friend and former colleague, Erica Sadun, is about to release the third edition of her book on iPhone and iOS programming. It’ll be out in January and I have no doubt it will rock.
  • Programming in Objective-C 2.0 — This is the bible for users who want to go in depth with Objective-C 2.0. The principles are often applied to Mac OS X programming, but they carry over to iOS programming too. A third edition of this book is expected in early 2011.
In all honesty, the iOS Dev Center is probably the best resource on the Internet. Apple has a seriously in-depth resource library, reference list, sample code library and there is a developer forum where you can interact with other iOS developers and Apple engineers. However, you do have to be a member of the iOS Dev Program to get access to much of the best stuff. If you haven’t paid your $99 yet, check out these online communities:
  • iPhone Dev Forums — This is a solid site that is moderately active, and a good place to go for lists of resources.
  • iPhone Dev SDK — This is a fairly active forum with lots of channels to discuss various topics surrounding iPhone development and the business side of iPhone development.
  • iPhone-Developers.com — From the team behind XDA Developers (see below) comes iPhone Developers, a new forum and community focused on the iPhone.
Note: You need a Mac in order to develop for iOS. There are a few tools, like Adobe’s Flash to iPhone tool that will work in Windows, but in order to submit your application, run Xcode and test on the emulator, you need to be using a Mac.
 

Sunday 14 October 2012

Beginning Android - Install an Android Platform

Google provides various Android platforms that can be installed via the SDK’s SDK Manager tool. Lesson 2 shows you how to use SDK Manager to install the Gingerbread platform (version 2.3.3) and platform tools.

Note Gingerbread is a code name for Android 2.3 and minor updates (e.g., 2.3.3). Google is in the habit of naming its platforms after dessert items.

Start the Android SDK Manager Application


Start SDK Manager (or android, which is one of the basic tools). After a few moments, you will see this application’s Android SDK Manager window with content similar to that shown in Figure

Android SDK Manager lets you install or remove Android platforms and other items.

Android SDK Manager presents a user interface organized into a menubar and a content area. The menubar presents Packages and Tools menus:
  • The Packages menu presents menuitems for displaying some combination of updated or new packages (Android components), installed packages, and obsolete packages. It also presents menuitems for sorting the list of packages by API level or repository, and for reloading the list of packages shown in the content area.
  • The Tools menu presents menuitems for managing Android Virtual Devices (device configurations that are run with the Android emulator) and add-on sites, for specifying options related to proxies (computers or applications that sit between networks as intermediaries) and other items, and presenting about information.
The content area presents the SDK’s path, a table of package information, checkboxes for determining what categories of packages to display, radio buttons for selecting how packages are sorted, buttons for installing and deleting packages, and a progress bar that displays the progress made by SDK Manager as it scans Google’s servers for package information (at startup and when Reload is selected from Packages).

Install Gingerbread 2.3.3 and Platform Tools


Uncheck Android 4.0.3 (API 15), which automatically unchecks all of the checkboxes underneath in its hierarchy. Instead, check Android 2.3.3 (API 10), which automatically checks all of the checkboxes underneath, and check Android SDK Platform-tools as well. You should end up with the user interface shown in Figure


Android SDK Manager’ s Install button reports that there are 22 packages to install.

The Install button identifies 22 packages to be installed. This count includes the Google USB Driver package in the Extras section (at the bottom of the window). You can uncheck this package if you don’t have an actual Android device and plan to do all of your development via the Android emulator. However, you might as well keep it checked.
Click Install and you will encounter Figure 4’s Choose Packages to Install dialog box.


 Green checkmarks appear beside those packages that will be installed.

The Choose Packages to Install dialog box presents a list of packages along with information about the highlighted package in the pane on the list’s right. The Accept and Reject radio buttons let you accept or reject the highlighted package. You can accept all packages by selecting the Accept All radio button.
The Accept button for a package with a green checkmark beside its name is selected. Neither the Accept nor Reject button is selected when a questionmark appears. This is certainly true for the Google USB Driver package. You will need to highlight this package and select its Accept radio button to ensure that it’s installed (assuming that you want to install this component).
Click Install to install all checked packages. Figure displays the Android SDK Manager Log window that appears over the Android SDK Manager window, and which provides installation details. It also shows a progress bar that reveals the amount of progress made in installing all selected packages.


Download progress appears on both the Android SDK Manager Log window and (at the bottom of) the Android SDK Manager window.

Figure includes a “Stopping ADB server failed (code -1).” message. ADB stands for Android Debug Bridge, which is a tool consisting of client and server programs that let you control and interface with your Android device. This message appears because the ADB server isn’t running at this point.
During installation, you will probably encounter Figure ADB Restart dialog box.


If you haven’t developed for Android before, the ADB server won’t be running and there’s no point in restarting it now. Therefore, click the No button.
After installation finishes, you’ll see a “Done loading packages.” message at the bottom of the Android SDK Manager and Android SDK Manager Log windows. Close Android SDK Manager Log.
Because Android SDK Manager’s user interface is somewhat buggy, its Install button continues to show that packages need to be installed. You can eliminate this confusion by unchecking and then checking both of the Updates/New and Installed checkboxes.
Figure shows the packages that should be installed. You don’t have to have the Google UDB driver installed unless you plan to install and test your apps on a real Android device.


Select the Installed checkbox to view only installed packages.

Android Development - How To Make Your App Respond to SMS Messages

Now, we are going to create an app that will respond when an SMS is received. This app is going to only display the incoming message on a Toast.

Step 1: Create a New App

For this app, we are going to create a BroadcastReciever to catch the in coming SMS message. Though we are not creating an activity for this, generally such apps can create an activity for the settings page of such apps.
The following is the AndroidManifest.xml for this app:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="recieveSMS.com"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
    </application>
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
</manifest>

Here, we add the android.permission.RECEIVE_SMS permission in our app so that we can respond to SMS received.

Step 2: Creating the SMS Receiver

The code for the SMS receiver is as follows:

package recieveSMS.com;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
public class RecieveSMS extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        Bundle bundle = intent.getExtras();
        SmsMessage[] recievedMsgs = null;
        String str = "";
        if (bundle != null)
        {
            Object[] pdus = (Object[]) bundle.get("pdus");
            recievedMsgs = new SmsMessage[pdus.length];
            for (int i=0; i                recievedMsgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                str += "SMS from " + recievedMsgs[i].getOriginatingAddress()+ " :" + recievedMsgs[i].getMessageBody().toString();
            }
            Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
        }
    }
}

We have to create a class which extends BroadcastReceiver, and we have to override the onRecieve Method.
In the onRecieve method, we remove the data from the received Intent, remove the SmsMessage object, and obtain the sender’s address and text to display on a toast.

Step 3: Running the App

To test this, you will need two Android emulator instances. We will send the SMS using an SMS app from one instance to the other. You will be able to see the Instance number on the top. As seen below, the numbers that I have are 5554 and 5556.
So from the second Instance, I will send an SMS to the first instance as shown below:


Once the first instance receives an SMS, the information will be displayed as a Toast, as shown below:




SMS is become such an integral and important part of our mobiles today that there could be numerous different ways in which SMS can be integrated in your next killer Android app. The usability as well as the capabilities of you Android apps can be increased tremendously if SMS is properly integrated.
As seen above, Android as a platform provides very good support to integrate SMS in your applications. So, go out there and integrate SMS into you next awesome Android app!

How to Send SMS Directly Via the API Provided by Android

Now, we are going to create an app where DirectSendSMS will be the enhanced version of the previous app. This app will directly send the “hello” message to the user using the Android SMS API.

Step 1: Creating the UI and Layout

First we need to create a new activity, DirectSendSMS. The UI of this app is going to be the same as the one described above, so for this also we will create a linear lay out and add one Textiew, one EditText, and one button.
The layout is as follows:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="2dip"
android:paddingRight="4dip"
android:text="Recipient Number"
/>
<EditText android:id="@+id/messageNumber"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:cursorVisible="true"
android:editable="true"
android:singleLine="true"
/>
<Button android:id="@+id/sayhello"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Say Hello!"
android:onClick="sayHello"
/>
</LinearLayout>
 

Step 2: Initializing the Activity

The initializing of the activity is also same as described in the previous app. Within the onCreate function, we set the main layout as the content view and take the EditBox in a private variable.

public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      messageNumber=(EditText)findViewById(R.id.messageNumber);
  }

Step 3: Specifying the Permission for Sending the SMS

In Android, one has to specify all of the permissions needed by the app in the AndroidManifest.xml. By doing so while installing the app, all the permissions required by the app will be shown to the user.
For the ability in our app to send messages, we need to add the android.permission.SEND_SMS permission into AndroidManifest.xml as follows:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="directSendSMS.com"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".DirectSendSMS"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
<uses-permission android:name="android.permission.SEND_SMS">
    </uses-permission>
</manifest>
 

Step 4: Sending the SMS

public void sayHello(View v) {
    String _messageNumber=messageNumber.getText().toString();
    String messageText = "Hi , Just SMSed to say hello";
    SmsManager sms = SmsManager.getDefault();
    sms.sendTextMessage(_messageNumber, null, messageText, null, null);
}

In the sayHello function, we get the number that the user entered. In a variable, we hold the message text that we want to send. Then, we get the SmsManager object as follows:

SmsManager sms = SmsManager.getDefault();


Then, using the sendTextMessage method of SmsManager, we send the message.

 

Step 5: Displaying a Toast When the Message is Successfully Sent

public void sayHello(View v) {
        String _messageNumber=messageNumber.getText().toString();
        String messageText = "Hi , Just SMSed to say hello";
        String sent = "SMS_SENT";
        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
            new Intent(sent), 0);
        //---when the SMS has been sent---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                if(getResultCode() == Activity.RESULT_OK)
                {
                  Toast.makeText(getBaseContext(), "SMS sent",
                                Toast.LENGTH_SHORT).show();
                }
                else
                {
                    Toast.makeText(getBaseContext(), "SMS could not sent",
                            Toast.LENGTH_SHORT).show();
                }
            }
        }, new IntentFilter(sent));
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(_messageNumber, null, messageText, sentPI, null);
    }

Now, we have enhanced the sayHello method to display a Toast upon successfully sending the message. We create a new PendingIntent for this and pass it as an argument to the sendTextMessage method. We also register a receiver for this intent, which checks the result code and displays a Toast saying SMS sent.

Now, the app will look like the following:

How to Handle SMS in Android Development

SMS is an integral part of mobile devices and mobile applications. An overwhelming majority of mobile users use the SMS service on their mobiles; some use it dozens of times per day. Android provides a very good API so that developers can integrate SMS technology into their apps, increasing the utility and appeal of their applications. In this article we are going to examine several apps that use SMS technology via the APIs provided by Android.
 

How to Launch the SMS Application From Your Program.

We are now going to create a small app which will say “hello” to our friends by sending an SMS message. This app will take the friend’s number from the user, then the application will launch the SMS application of the mobile phones with the number the user entered, and finally it will send a “hello” message.

Step 1: Creating the UI and layout

First, create a simple activity called as LaunchSMS , then we will create the lay out as follows:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="2dip"
android:paddingRight="4dip"
android:text="Recipient Number"
/>
<EditText android:id="@+id/messageNumber"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:cursorVisible="true"
android:editable="true"
android:singleLine="true"
/>
<Button android:id="@+id/sayhello"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Say Hello!"
android:onClick="sayHello"
/>
</LinearLayout>

Above, we have created a linear layout with one TextView to tell the user that he has to enter the recipient’s number. Then, we have one EditText to take in the number from the user, and one button which, when clicked, will call the method sayHello.

The code for the activity is as follows:

package launchSMS.com;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class LaunchSMS extends Activity {
    /** Called when the activity is first created. */
    private EditText messageNumber;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        messageNumber=(EditText)findViewById(R.id.messageNumber);
    }
    public void sayHello(View v) {
        String _messageNumber=messageNumber.getText().toString();
        String messageText = "Hi , Just SMSed to say hello";
        Intent sendIntent = new Intent(Intent.ACTION_VIEW);
        sendIntent.setData(Uri.parse("sms:"+_messageNumber));
        sendIntent.putExtra("sms_body", messageText);
        startActivity(sendIntent);
    }
}

Step 2: Initializing the Activity

Using the onCreate method, we will set main layout we created as the content view. Then, I have created a private member to hold the EditBox for the message number.

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        messageNumber=(EditText)findViewById(R.id.messageNumber);
    }

The UI for the app will look as follows:



Step 3: Launching the SMS App

public void sayHello(View v) {
		String _messageNumber=messageNumber.getText().toString();
		String messageText = "Hi , Just SMSed to say hello";
		Intent sendIntent = new Intent(Intent.ACTION_VIEW);
		sendIntent.setData(Uri.parse("sms:"+_messageNumber));
        sendIntent.putExtra("sms_body", messageText);
        startActivity(sendIntent);
	}
 
In the function sayHello, we first get the number which the user has entered in the EditText. Then, we create a String variable to hold the message text that we want to send.

Now, to launch the SMS application, we have to create the following:

Intent sendIntent = new Intent(Intent.ACTION_VIEW);





Then, we set the intent data with the number entered by the user as follows:

sendIntent.setData(Uri.parse("sms:"+_messageNumber));

Finally, the message text goes as extra data in the intent using the method putExtra on the intent.

sendIntent.putExtra("sms_body", messageText);

Then, the intent is sent by passing the created intent to startActivity. This will launch the SMS application of the user with the number and message text already prepopulated. The user can make edits if he or she wants, and then they will just have to press “send” to send the message to his or her friend.

So, using the intents, we can launch the SMS app from within our program. Enjoy ...

Saturday 13 October 2012

Beginning Android - Launching the Android Virtual Device

An Android Virtual Device (AVD) is a device configuration that is run within the Android emulator. It works with the emulator to provide a virtual device-specific environment in which to install and run Android apps. This tutorial shows you how to launch the previously created AVD via the Android SDK’s AVD Manager tool.

Using AVD Manager to Launch an AVD

Assuming that you’ve created MyAVD, you’ll want to launch this AVD with the emulator. Begin by running the Android SDK’s AVD Manager tool, or run SDK Manager and select Manage AVDs from the Tools menu. You should see an Android Virtual Device Manager window that’s similar to Figure
 
 
Android Virtual Device Manager presents a list of previously created AVDs, of which there is only MyAVD in Figure. Highlight this AVD, which enables the Start button, and click this button to begin the process of launching MyAVD. Figure shows you the resulting Launch Options dialog box.
 
 
As well as identifying the skin and screen density of the AVD that’s about to be launched, Launch Options presents the following checkboxes:
  • Scale display to real size causes the resolution of the emulator’s display to be scaled to match the screen size (in terms of inches and dots per inch) of the physical Android device being emulated, when checked.
  • Wipe user data causes the AVD’s user-data partition to be deleted, when checked. (The emulated device preserves apps and state data across AVD restarts in a user- data partition. You might occasionally need to delete this partition while developing and testing an app, and you do so by checking Wipe user data.)
  • Launch from snapshot causes the emulated device to be started from a previously saved snapshot of the device’s state, when checked. This checkbox defaults to being checked for an AVD created with snapshot enabled.
  • Save to snapshot causes the emulated device’s state to be saved to a snapshot upon device exit, when checked. This checkbox defaults to being checked for an AVD created with snapshot enabled.
The final two checkboxes refer to a snapshot, which is a stored file of emulator state. The emulator launches much faster when launched from a snapshot.

Keep the settings that are shown in Figure and click the Launch button. On a Windows XP platform, you will see a few command windows flash by and then you’ll see Figure emulator window.


Figure shows the emulator window with 5554:MyAVD in its titlebar. Value 5554 identifies a console port that you can use to query and control the AVD’s environment. Android supports a maximum of 16 concurrently executing AVDs, where each AVD is assigned an even-numbered port number that starts at 5554. (A discussion of the console is outside the scope of this lesson.)
Figure also shows that the emulator window consists of a device screen on the left and phone controls/keyboard on the right. The device screen initially displays “A N D R O I D _”, and then displays the graphical logo shown in Figure while the Android platform associated with the AVD is initializing.


The graphical ANDROID logo has an animated shimmer effect.

After several minutes, this logo is replaced with the home screen that’s shown


The home screen is a special app that displays a wallpaper background. A statusbar appears above the home screen (and every app screen), presenting access to notifications, the amount of battery power that’s remaining, the current time, and other information.
The home screen can display widgets, which are miniature app views that can be embedded in this screen or the screen of any other app. Figure reveals the Google Search widget near the top of the home screen.

Beginning Android - Create an Android Virtual Device

An Android Virtual Device (AVD) is a device configuration that is run with the Android emulator. It works with the emulator to provide a virtual device-specific environment in which to install and run Android apps. Lesson 4 shows you how to create an AVD by introducing you to the Android SDK’s AVD Manager tool.

Using AVD Manager to Create an AVD

The Android SDK provides the AVD Manager tool for creating and otherwise managing AVDs. You can run this tool directly or run SDK Manager and select Manage AVDs from the Tools menu. In either case, you are greeted with the Android Virtual Device Manager window
 
 
Android Virtual Device Manager lets you create, update, delete, repair, and start AVDs. Click the New button to create a new AVD. This application responds by presenting the Create new Android Virtual Device (AVD) dialog box
 
 
AVD has a name, targets a specific Android platform, and has other features. Enter MyAVD as the name, select Android 2.3.3 – API Level 10 as the target platform, and choose a size of 100 (megabytes) for the Secure Digital (SD) card. Apps store their data in hierarchical structures on this card.
 
Note: Check the Enabled checkbox in the Snapshot section if you want to persist the emulator’s state between emulator executions. Doing so lets you quickly start the emulator after the first startup.
 
reveals that you can choose the virtual device’s skin (appearance). When you select Android 2.3.3 – API Level 10 as the target platform, the skin defaults to the built-in WVGA800 value. Furthermore, it presents the following hardware properties:
  • Abstracted LCD Density, set to 240 dots per inch
  • Max VM application heap size, set to 24 megabytes
  • Device RAM size, set to 256 megabytes
Tip: If you plan to run the virtual device on a platform whose screen size is set to 1024 x 768, you’ll find that you cannot see the virtual device’s entire screen without scrolling. In this case, you should set the skin to a lower value, such as HVGA (which also changes the Abstracted LCD Density to 160).

Click the Create AVD button after making these changes. You should see the confirmation dialog box that appears


Click the OK button to dismiss this dialog box and return to Android Virtual Device Manager’s main window. You should see the new AVD listed as shown in Figure


If you ever want to change this AVD’s characteristics, highlight its entry in the list and click the Edit button. You can also obtain a description of the AVD by clicking Details, and you can delete it by clicking Delete.

Store User Data Using Simple Text Files and APIs in Android

Creating the UI of the File Store App

Lets start by creating a simple app that shows an text editor and allows the user can input any text to be saved as a file.The saved text will be saved within the text editor next time the application is started by reading from the storage file.
First, we’ll create the UI for the app. Within the UI we are going to create a text editor and a save button on screen.
The layout for this UI is as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Enter the text"
/>
<EditText
android:id="@+id/textbox"
android:singleLine="false"
android:gravity="top"
android:lines="10"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<Button android:id="@+id/save"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Save the notes"
android:onClick="saveClicked"/>
</LinearLayout>






Above, we create a text view using the tag <TextView>, which just displays the text as “Enter The Text”.
Next, we create an editor to take in the text from the user. We create this using the <EditText> tag, and because we want the text to be multi-line, we also set the properties android:singleLine=“false” and android:lines=“10″ on the EditText. Then, we create a button using the <Button> tag, which will be used to save the modified text to a file.
Once the layout is created, we’ll use the function onCreate to set this layout of the content view as follows:

public class FileDemo extends Activity {
/** Called when the activity is first created. */
private final static String STORETEXT="storetext.txt";
private EditText txtEditor;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtEditor=(EditText)findViewById(R.id.textbox);
}
}
 
Now, if we run the app, the UI will look as follows:


Saving the File

Once the UI is done, we need to add functionality to save the text contents to a file upon pressing the “Save” button. To do this, the code is as follows:

public void saveClicked(View v) {
try {
OutputStreamWriter out=
new OutputStreamWriter(openFileOutput(STORETEXT, 0));
out.write(txtEditor.getText().toString());
out.close();
Toast
.makeText(this, "The contents are saved in the file.", Toast.LENGTH_LONG)
.show();
}
catch (Throwable t) {
Toast
.makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
.show();
}
}
 
Once “Save” is clicked, the function saveClicked is called. In the function saveClicked, we open a file using the Android API openFileOutput by passing it the name of the file to open, which we defined in our class as

private final static String STORETEXT="storetext.txt";

Then, we create an object of OutputStreamWriter using the output of openFileOutput.
Finally, we get the text of the text editor and pass it to the write method of our OutputStreamWriter to write it to the file. Once the text is written to the file, we show a Toast to indicate that the text is saved. Below, the Toast reads “The contents are saved in the file.”


Reading the Text File Upon App Load

Now, let’s write a function that reads this newly-created file and populates the text editor with the contents of the file. We will call this function in the onCreate function so that as soon as the app launches, the editor is filled with the information from the file. The function is as follows:

public void readFileInEditor()
{
try {
InputStream in = openFileInput(STORETEXT);
if (in != null) {
InputStreamReader tmp=new InputStreamReader(in);
BufferedReader reader=new BufferedReader(tmp);
String str;
StringBuilder buf=new StringBuilder();
while ((str = reader.readLine()) != null) {
buf.append(str+"\n");
}
in.close();
txtEditor.setText(buf.toString());
}
}
catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
}
catch (Throwable t) {
Toast
.makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
.show();
}
}

In this function, we first open the file with the API openFileInput, and then we create an InputStream from it. From that, we create an InputStreamReader and a BufferedReader. Using the BufferedReader, we read line after line the text of the storage file, and we store the text in the buffer. Once the whole file is read, we send the text into the editor. Now, if the application is run, the application will load the the editor filed with the contents of the file, as shown below.

Beginning Android - Developing Apps with Eclipse

Installing Eclipse

According to Google’s system requirements, you must install an Eclipse 3.6 (Helios) or greater package that includes the Java Development Tools (JDT) plugin. Google recommends that you install one of the following packages:
  • Eclipse IDE for Java Developers
  • Eclipse Classic
  • Eclipse IDE for Java EE Developers

The eclipse.org website makes several IDE packages that meet different requirements available for download. I chose to download Eclipse Classic 3.7.1 for the Windows XP platform.
Assuming that you are also running Windows, point your browser to the Eclipse Classic 3.7.1 web page (http://www.eclipse.org/downloads/packages/eclipse-classic-371/indigosr1), and then perform the following steps to download and install this package:

  • Eclipse IDE for Java Developers
  • Eclipse Classic
  • Eclipse IDE for Java EE Developers

The eclipse.org website makes several IDE packages that meet different requirements available for download. I chose to download Eclipse Classic 3.7.1 for the Windows XP platform.
Assuming that you are also running Windows, point your browser to the Eclipse Classic 3.7.1 web page (http://www.eclipse.org/downloads/packages/eclipse-classic-371/indigosr1), and then perform the following steps to download and install this package:

  1. Select the appropriate distribution file for your platform by clicking one of the links in the Download Links box on the right side of this page. For example, I clicked Windows 32-bit.
  2. Click a download link, select a download mirror, and save the distribution file to your harddrive. For example, I saved eclipse-SDK-3.7.1-win32.zip to my hard drive.
  3. Unarchive the distribution file and move the eclipse home directory to a convenient location. For example, I moved eclipse to my C:\Program Files directory.
  4. Create a desktop shortcut to the eclipse application located in the eclipse home directory. This shortcut makes it convenient to launch the Eclipse IDE.

Note: An Eclipse workspace is a disk location that’s associated with a workbench instance, where a workbench is a runtime instance of the Eclipse IDE. The workspace contains files, folders, and other resources that comprise your projects.



Click OK to close Workspace Launcher. Eclipse responds by performing some initialization, and then it presents its main window


The main window is divided into a menubar, a toolbar, a workbench area (initially presenting a Welcome tab), and a statusbar.

Install the ADT Plugin

The Android Development Tools (ADT) Plugin is a special Eclipse plugin that facilitates app development. Although you can develop Android apps without the ADT Plugin, you’d have to work directly with Android’s command-line tools. You’ll find that this plugin makes it much faster and easier to create, debug, and otherwise develop these apps.
The ADT Plugin offers the following benefits:
  • It gives you access to other Android development tools from inside the Eclipse IDE. For example, ADT lets you access the many capabilities of the Dalvik Debug Monitor Server (DDMS) tool, which lets you take screenshots, set breakpoints, manage port-forwarding, and view process and thread information directly from Eclipse.
  • Its New Project Wizard helps you quickly create and setup all of the fundamental files that you’ll need for a new Android app.
  • It automates and simplifies the app-building task.
  • Its Android code editor helps you write valid XML for your Android manifest and resource files.
  • It facilitates exporting your project as a signed APK, which can then be distributed to users.
Assuming that the Eclipse IDE is running, complete the following steps to install the latest ADT Plugin revision:
  1. Select Install New Software from the Help menu.
  2. Click the Add button on the resulting Install dialog box’s Available Software pane.
  3. On the resulting Add Repository dialog box, enter Android Plugin into the Name textfield and https://dl-ssl.google.com/android/eclipse/ into the Location textfield. Click the OK button.
  4. After a few moments, you should see Developer Tools in the tree-based list near the middle of the Install dialog box. Expand this node and check the checkbox to its left. You’ll discover that the Android DDMS, Android Development Tools, Android Hierarchy Viewer, and Android Traceview subnodes are also checked. Click the Next button.
  5. After a few moments, an Install Details pane appears and signifies that these four items will be installed. Click Next, and the Review Licenses pane appears. Read and accept the terms of these license agreements and click the Finish button.
  6. An Installing Software dialog box appears, giving you the option of installing these items in the background. If you encounter a Security Warning dialog box, click the OK button to close this dialog box and continue.
  7. Eclipse presents a Software Updates dialog box that prompts you to restart this IDE. Click the Restart Now button. After Eclipse restarts, you will probably see an Android SDK Verification dialog box stating that Eclipse cannot find the C:\android-sdk-windows folder. This is not surprising, because the folder is named C:\android-sdk (as specified earlier in this course when installing the SDK). Ignore this error; you will fix it shortly. Click the OK button to dismiss this dialog box.
  8. Select Preferences from the Window menu to open the Preferences dialog box. For Mac OS X, select Preferences from the Eclipse menu.
  9. Select the Android node in the left panel of this dialog box.
  10. Click the Browse button beside the SDK Location textfield, and then locate your downloaded SDK’s home directory (e.g., C:\android-sdk) via the resulting Browse For Folder dialog box.
  11. After closing Browse For Folder, click Apply followed by OK on the Preferences dialog box to complete installation.

Develop and Run W2A with Eclipse/ADT

Now that you’ve installed Eclipse and the ADT Plugin, let’s revisit W2A by developing this app in this new environment. We’ll begin by creating a W2A project, which is accomplished by performing the following steps:
  1. Start Eclipse if not running.
  2. Select New from the File menu and Project from the resulting popup menu.
  3. On the resulting New Project dialog box, expand the Android node in the wizard tree (if not expanded), choose the Android Project branch below this node, and click the Next button.
  4. On the resulting New Android Project dialog box, enter W2A into the Project Name textfield – the entered name identifies the current workspace directory in which this project is stored. Continuing, select the Create new project in workspace radio button if not selected, and click the Next button.
  5. On the resulting Select Build Target pane, ensure that Android 2.3.3 is checked under Build Target and click Next.
  6. On the resulting Application Info pane, enter Welcome to Android into the Application name textfield, replacing the default W2A value. This human-readable title appears as the app’s icon’s caption on the Android device’s app launcher screen. (You could leave W2A alone if desired.) Next, enter ca.tutortutor.w2a into the Package Name textfield, check the Create Activity checkbox if not checked, enter W2A as the name of the app’s starting activity in the textfield that appears beside this checkbox, and make sure that 10 (Android 2.3.3) is current in the Minimum SDK drop-down listbox – it probably will be current. Click the Finish button.
Eclipse creates a W2A directory within its workspace directory. W2A contains the following subdirectories and files:
  • .settings: This directory contains org.eclipse.jdt.core.prefs. This file records project-specific settings.
  • assets: This directory stores an unstructured hierarchy of files. Anything placed in this directory can be retrieved by an app via a raw byte stream.
  • bin: This directory stores the created APK file.
  • gen: This directory stores the generated R.java file within a subdirectory structure that reflects the package hierarchy (ca\tutortutor\w2a).
  • res: This directory stores app resources in various subdirectories.
  • src: This directory stores app source code according to a package hierarchy.
  • .classpath: This file stores the project’s classpath information so that external libraries on which the project depends can be found.
  • .project: This file contains project-oriented information such as the name of project and what builders it contains.
  • AndroidManifest.xml: This file contains W2A’s manifest information.
  • proguard.cfg: This file contains configuration data for the ProGuard obfuscation tool.
  • project.properties: This file contains project settings.
Close the Welcome tab.


The workbench is organized around a menubar, a toolbar, several windows such as Package Explorer and Outline, a blank area that’s reserved for editor windows, and a statusbar.
Package Explorer appears on the left and presents an expandable list of nodes that identify the current workspace’s projects. To learn how Eclipse organizes the W2A project, click the “+” icon on the W2A node’s left. Figure 23 reveals an expanded project hierarchy.


Expand the src node followed by the resulting ca.tutortutor.w2a node. Double-click the resulting W2A.java node and you’ll see Figure editor window.


Then select Run or Run Last Launched from the menubar’s Run menu (Run appears instead of Run Last Launched if the project has not previously run). On the resulting Run As dialog box (which appears the first time you run the project), select Android Application and click OK. The W2A project is built before it runs.


W2A is successfully installed and run on the emulator in the context of Eclipse. Enjoy ...