Java + Android Development
This is my blog about Java, and Android software development. All the sample source code here are hosted at Kenai.com
Wednesday, March 6, 2013
Thursday, January 17, 2013
Wednesday, December 19, 2012
Google I/O 2011: HTML5 versus Android: Apps or Web for Mobile Development?
Actually there are lot of articles written already about this HTML5 vs. Android (or which one you should use in your mobile project). Just watch this video and take a look at this article Multi-platform Frameworks Destroy Android UX written by Juhani Lehtimäki.
Labels:
Android
Tuesday, October 16, 2012
Tuesday, July 17, 2012
Tuesday, July 3, 2012
Android Design Session Videos - Google I/O 2012
These are the Android design sessions videos from Google I/O 2012. These are worth watching!
Google I/O 2012 - Android Design for Success
Google I/O 2012 - So You've Read the Design Guide; Now What?
Google I/O 2012 - Navigation in Android
Google I/O 2012 - Advanced Design for Engineers
Labels:
Android,
Android Design
Tuesday, June 26, 2012
Beginning Android Part 4 - Apache Cordova Persistence Support
| Revision History Latest: Revision 0.5 - Aug. 15, 2012 |
||
|---|---|---|
| Revision 0.0 |
2012.06.26 |
|
| Revision 0.1 |
2012.07.04 |
|
| Revision 0.2 |
2012.07.08 |
|
| Revision 0.3 |
2012.07.15 |
|
| Revision 0.4 |
2012.07.30 |
|
| Revision 0.5 |
2012.08.15 |
|
Persistence is a mean of saving applications state and it is one of the most important qualities necessary to reuse an application. Imagine what it would be like if an application like word processors such as Microsoft Office, OpenOffice does not have the quality of saving your documents, or an image manipulation program such as GIMP cannot save your images! An application can save its state into a datastore. The datastore can be a relational databases (RDBMS) such as MySQL, or a flat-file or an XML files.
Android Storage Quickview
Android supports many storage options for you to save your persistent application data. It is important for you to carefully read the official Android Storage Options documentation.
Android data storage options are the following:
- Shared Preferences - Store private primitive data in key-value pairs.
- Internal Storage - Store private data on the device memory.
- External Storage - Store public data on the shared external storage.
- SQLite Databases - Store structured data in a private database.
- Network Connection - Store data on the web with your own network server.
Persistence Strategy: What kind of data storage should I use?
The decision about which of the Android storage options you choose is usually determined by the following:
- Application Properties - You can use SharePreferences here.
- Database - You should use SQLite if you need to store structured data.
- Filesystem - You can use the Internal/External storage options.
This tutorial will focus on storage options provided by Apache Cordova to store structured data in a database.
Apache Cordova - Android
Apache Cordova is an HTML5 app platform that allows you to author native applications with web technologies and get access to APIs and app stores.
In this article, we will:
- Briefly covered the two feasible options of Cordova for offline storage on mobile devices
First - Please carefully read the CordovaStorage documentation along with W3C spec for Web SQL Database support. The W3C docs helped fill in some things that the Cordova documentation didn’t cover such as the error and labels forSQLError.
Working Offline: Caching
Cordova provides two feasible options for persisting your applications data: LocalStorage and Web SQL.
Web SQL is a thin, asynchronous wrapper around an SQLite database which is currently well-implemented on first-class mobile devices (iOS, Android, and BlackBerry OS 6.0). Note thatWebSQL is not supported on Firefox and IE. The WebSQL spec was deprecated in Nov. 18, 2010.
Web SQL offers a useful interface for storing structured data, it works well if you have a remote server that uses a SQL databases and you want to mirror the structure of your data between platforms. I will use this Web SQL standards in my demo application because it is fast and heavy-duty and because the storage size of SQLite is much bigger compare to local storage and well-implemented on first-class mobile devices such as Android.
Time for Action: A Simple To-Do Application
Ok, so let’s talk about the application. My demo application is called TodoListPhoneGap. It only allows you to add a task (it is your assignment to add the other functionality). You can checkout the source code by issuing the following command on terminal:
Once you’ve checked out the TodoListPhoneGap project, open it with Eclipse.
1. The first thing we need to do when using Cordova is to get a reference to our database, using the openDatabase function:
function createTaskDB() {
db = window.openDatabase("TaskDB", "1.0", "Simple Tasks", 1000000);
}
The openDatabase function requires four parameters: the name of the dabase, the version of the database, the display name of the database, and the size in bytes of the database.
2. The next step is to create a table to store our records. To do this, we will start a transaction on ourdb, and execute the SQL query asynchronously:
// start transaction on out db
db.transaction(createTable, sqlErrH, getTaskList);
The function transaction accepts three parameters: the function that will executes the SQL query, the function to handle the errors (if any), and the function to call when transaction is successful.
function createTable(tx) {
tx.executeSql("CREATE TABLE IF NOT EXISTS task (id unique, taskname)");
}
3. Finally, we need to populate and query the table in our db. To do this, we will start a transaction again on our db, but this time we will pass a DML (Data Manipulation Language such as INSERT, UPDATE, SELECT, DELETE) instead of DDL (Data Definition Language such as CREATE, DROP, ALTER).
db.transaction(function(tx) {
tx.executeSql("INSERT INTO task (taskname) VALUES (?)",[ task.taskname ]);
}, sqlErrH, cb);
Running The Demo Application
Running The Demo Application as Dolphin Garage Web-App
Dolphin announced its Garage Open API at Google I/O 2012. PhoneGap and Dolphin browsers recently team up.
“With the new Dolphin PhoneGap APIs and Add-on, you can easily create web app from scratch or from existing Android Apps. Users simply navigate to a web site that, like a conventional package, makes full use of local features such as camera, GPS, and accelerometer. The Dolphin PhoneGap Add-on enables JavaScript on a webpage to access local device features.”
Steps to run my demo application as a thin-client web-app for Dolphin users:
1. Checkout my demo application using SVN
2. Copy the files located in <your project's name>/assets/www to your web server (i.e. Tomcat)
4. Make changes to index.html. Just replace js/cordova-1.5.0.js with js/cordova.dolphin.js
5. Run your web-server.
6. Test the demo application:
- Download Dolphin Browser HD and the PhoneGap add-on.
- Access <your webserver>/TodoListPhoneGap using the Dolphin Browser HD.
The first approach shows you how to run my demo application as an Android Application Package (APK). Usually, the APK’s are release through marketplace such as Google Play.
The second approach shows you how to deploy my demo application to your web-server.
And that’s pretty much it. There’a a lot more you can do with PhoneGap. In this article you learned how to:
1. Persist application state by using the Web SQL standards.
2. Use Dolphin Garage API.
Further Reading:
THE ENTERPRISE DILEMMA: NATIVE VS. WEB APPS
MOBILE TODAY: NATIVE, WEB or HYBRID?
http://community.developer.motorola.com/t5/MOTODEV-For-Enterprise/Mobile-Today-Native-Web-or-Hybrid-nativevsweb/ba-p/24204
Sunday, April 8, 2012
Kick-starting Android Projects with Maven 3 and Android Connector for M2E
This screencast shows how to create an Android project from command line with Maven 3 and Android Connector for M2E. You need to install Maven and Android Connector for M2E in Eclipse Marketplace for this purpose.
Thank You!
Thank You!
Sunday, March 4, 2012
Beginning Android (Part 3) - Monetizing Android Apps
| Revision History Latest: Revision 0.6 - July 31, 2012 |
||
|---|---|---|
| Revision 0.0 |
2012.03.03 |
|
| Revision 0.1 |
2012.04.23 |
|
| Revision 0.2 |
2012.04.24 |
|
| Revision 0.3 |
2012.04.26 |
|
| Revision 0.4 - 0.5 |
2012.05.02-03 |
|
| Revision 0.6 |
2012.07.31 |
|
Catch Up!
If you haven't seen the first and second part of this Beginning Android tutorial series, please take some time to read it before reading this article. Just click on the following links.
Introduction
The Google AdMob Ads provides application developers tools to promote, measure and monetize mobile apps. I created this screencast for you to learn how to add banner ads to your Android apps.Creating The AdMob Ads Android Project
To display banners in your Android app, simply add the AdMob SDK into your project and add a
com.google.ads.AdView to your UI.Dependencies and prerequisites
- Android 3.2 compiler or higher
- Android SDK
- Google AdMob Ads SDK for Android
Note: According to the official AdMob documentation you should make sure you have the latest copy of the Android SDK and that you're compiling against at least Android v3.2. Compiling against newer versions of Android doesn't mean your apps will not run on older versions of Android. You just have to make your apps backward compatible in terms of binary and functionality.
See What API Level Should I Target? If you are still compiling against significantly older versions of the SDK you are doing it wrong.
See What API Level Should I Target? If you are still compiling against significantly older versions of the SDK you are doing it wrong.
![]() |
| Error when compiling against API level older than 13 |
Setting Up The Banner
Incorporating the Google AdMob Ads into an Android project is easy. Simply follow these steps:- Sign up with AdMob and download the latest AdMob SDK.
- Add the AdMob SDK to your project build path.
- Setup the required network permissions and
com.google.ads.AdActivityinAndroidManifest.xml. - Setup the AdView instance.
AdMob Payment Details
When AdMob asks about your Payment Details you can tell AdMob to use your PayPal account as the payment method. Sign up for a PayPal account if you don't have one.
See How To Open PayPal Account
Ad Unit ID
You can retrieve this ID after you've finish setting up your Site/App in AdMob. Just go to your Site/App › Manage Settings.
When AdMob asks about your Payment Details you can tell AdMob to use your PayPal account as the payment method. Sign up for a PayPal account if you don't have one.
See How To Open PayPal Account
Ad Unit ID
You can retrieve this ID after you've finish setting up your Site/App in AdMob. Just go to your Site/App › Manage Settings.
Add The AdMob SDK To Project Build Path
Create a new folder named "libs" in your project root directory and paste the GoogleAdMobAdsSdk-x.x.x.jar there. Then simply right-click on the GoogleAdMobAdsSdk-x.x.x.jar, click Build Path › Add To Build Path in your Eclipse IDE.![]() |
Setup The Required Network Permissions and AdActivity in AndroidManifest.xml
Making an ad request requires the INTERNET and ACCESS_NETWORK_STATE permissions. Open AndroidManifest.xml (located in your projects root directory) and add the following permissions:![]() |
Setup the AdView instance
The AdView is simply a view displaying HTML5 ads that responds to user touch. An AdView (like any View in Android) may be created either purely in Java code or in XML. The following example uses XML.Open main.xml (located in <your project's name>/res/layout) and replace its contents with the code below:
![]() |
The project will build with error because it cannot find "@string/adMobId". Simply open strings.xml (located in /res/values/) and add the following code to resolve the error:
![]() |
Replace MY_AD_UNIT_ID with your actual Ad Unit ID and save the project. The project should be able to build without any errors.
All Done!
When you run the project you should see a banner at the top level of the screen:![]() |
If you have the command line Subversion client, you can checkout the repository by running:
svn co https://svn.kenai.com/svn/ron-os-sample-code~project-code-repository/BeginningAndroidProjects/AdMobAds
Creating The Banner In Pure Java
You now know how to create banner from XML. I created a new project called AdMobAds2, which is a modified version of AdMobAds project to show you how to create banner in pure Java.svn co https://svn.kenai.com/svn/ron-os-sample-code~project-code-repository/BeginningAndroidProjects/AdMobAds
svn co https://svn.kenai.com/svn/ron-os-sample-code~project-code-repository/BeginningAndroidProjects/AdMobAds2
Now checkout AdMobAds and AdMobAds2 project using any Subversion client and use a file comparison tool such as Meld to see the difference between the project.
![]() |
| We can see the diff between AdMobAds and AdMobAds2 project using Meld |
Once you've checked out the AdMobAds2 project, open it with Eclipse and take a look at the implementation of the onStart() method of AdMobAdsActivity.java.
![]() |
I instantiated a new AdRequest object at line 62. Then at line 65 to 71 I set the devices which will receive test ads only. I will not explain the detail of the Java code here because I assume you already know how to read and understand Java language. But there's one thing I would like to note, PLEASE DO NOT FORGET TO ADD YOUR ANDROID TEST DEVICE HASH ID IN strings.xml (located in /res/values/) as shown in screen-shot below:
![]() |
| Replace PLEASE_INSERT_YOUR_HASH_ID_HERE with you actual Android test device hash id |
This is important because you do not want to make wrong impressions and violate the terms and conditions of AdMob. The easiest way to find you Android device ID is to look at the LogCat and search for a message similar to this one:
I/Ads(5899): To get test ads on this device, call adRequest.addTestDevice("73CC3A21D...");
The quoted string is your hash device ID.
Thank You!
Thursday, March 1, 2012
Beginning Android (Part 2)
| Revision History Latest: Revision 0.5 - Apr. 21, 2012 |
||
|---|---|---|
| Revision 0.0 | 02.29.2012 |
|
| Revision 0.1 | 03.01.2012 |
|
| Revision 0.2 | 03.14.2012 |
|
| Revision 0.3 - 0.5 | 03.29.2012 04.10.2012 04.21.2012 |
|
Creating Your First Android Application
The first Android application I am developing is the BlueMine Starter Package in Google Play Store.
Part 1 of this Beginning Android tutorial series covered the overview of the Android platform. If you haven't seen it yet, please take some time to read it before reading this article.
In this article, you will develop your first Android application. You will learn how to send SMS programmatically within an Android application.
NOTE: This tutorial assumes that you are familiar with Java programming and IDE's like Eclipse and NetBeans.
Brief Contents
- The Four Components of Android
- Creating The SMS Application
- Obtaining The Required Tools
- Developing SendingSMS project
Why Develop for Android?
The Android (known as the iOS killer) has some huge advantages over other mobile operating system like the iOS, Symbian, Windows Phone, etc. If you take a look at the Android Ice Cream Sandwich you can say to yourself that its very revolutionary and innovative, isn't it? Android has Home-screen Widgets and other features you can't find in iOS or any other mobile operating system. You can develop powerful and innovative apps that integrates with its core applications such as Google Maps with Location-Based Services and more.
Android is free and open-source and it uses the #1 Java programming language.
The Four Components of AndroidThe Android (known as the iOS killer) has some huge advantages over other mobile operating system like the iOS, Symbian, Windows Phone, etc. If you take a look at the Android Ice Cream Sandwich you can say to yourself that its very revolutionary and innovative, isn't it? Android has Home-screen Widgets and other features you can't find in iOS or any other mobile operating system. You can develop powerful and innovative apps that integrates with its core applications such as Google Maps with Location-Based Services and more.
Android is free and open-source and it uses the #1 Java programming language.
Your Android projects should contain at least one class that is derived from one of these components:
- Activity - If your Android application has a UI, you must create one class that extends this component. You will learn how to create an Activity in this article.
- Service - If your Android application has a long running task, you should do it in the background and not in the UI thread. This class provides the facility to make a task run in the background.
- BroadcastReceiver - If your Android application will receive and respond to global events such as the sending and delivery of SMS, your class must be registered as a subclass of this component. You will learn how to use this component to get feedback after sending SMS.
- ContentProvider - If your Android application has data that you wants to share with other Android applications, you should create and implement this component.
For the detailed look at the Android Build process please refer to Android documentation.
Creating The SMS Application
Android development has four phases. Below is a diagram of Android development process:
![]() |
| http://developer.android.com/images/developing/developing_overview.png |
Obtaining The Required Tools
Before you can start creating Android application, you must setup your development environment first. You will need the following to develop our SMS application:
- Android SDK
- Eclipse (Helios or greater)
Note: You need to install at least the Android 1.6 platform for this tutorial.See Android Installation Instructions and System Requirements for more information and watch this video to learn how to setup your development environment for the first time on Windows.
I use Windows 7, Java 7, Eclipse Indigo for Java Developers, ADT and Android SDK revision 17 in this screencast.
Developing The SMS Project
SMS messaging is one of the killer applications on Android or any mobile phones today. Let's create your first simple and practical Android project. I assume that you are already familiar with Java programming here. I will not explain the detail of each line of code here. I'll give some instructions here that you should follow:
SMS messaging is one of the killer applications on Android or any mobile phones today. Let's create your first simple and practical Android project. I assume that you are already familiar with Java programming; I will not explain each line of code in detail.
Follow these steps:
Follow these steps:
1. Start your Eclipse IDE
2. Go to File -> New -> Project
3. Select Android Project in the New Project dialog
2. Go to File -> New -> Project
3. Select Android Project in the New Project dialog
4. Complete the New Android Project wizard.
5. Open main.xml (located in <your project's name>/res/layout) and replace its contents with the code below:
<?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" >
<EditText
android:id="@+id/editRecipient"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="14dp"
android:hint="@string/recipientHint"
android:inputType="phone" />
<EditText
android:id="@+id/editMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="17dp"
android:layout_toLeftOf="@+id/sendButton"
android:hint="@string/messageBodyHint" >
</EditText>
<Button
android:id="@+id/sendButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/editMessage"
android:onClick="send"
android:text="@string/sendButtonText" />
</RelativeLayout>
Note: I used RelativeLayout here because I need to align each common form component relative to the other components.6. Open SMSActivity.java (located in <your project's name>/src/<your package name>) and add the following code:
public void send(android.view.View view) {
final android.widget.EditText recipient = (android.widget.EditText) findViewById(R.id.editRecipient);
final android.widget.EditText message = (android.widget.EditText) findViewById(R.id.editMessage);
final android.telephony.SmsManager smsManager = android.telephony.SmsManager.getDefault();
final String addr = recipient.getText().toString();
final String text = message.getText().toString();
smsManager.sendTextMessage(addr, null, text, null, null);
recipient.setText("");
message.setText("");
}
7. To allow our application to send SMS, add the following permission to AndroidManifest.xml (located in your project's root directory):
<uses-permission android:name="android.permission.SEND_SMS" />
8. That's it. Deploy and run the project.
How It Works
Steps 1 to 4 show you how to create a new Android application in Eclipse. Steps 5 to 7 cover the code that will enable your new application to send SMS: step 5 changes the layout of your application's UI; step 6 includes the actual code that sends an SMS, and; step 7 includes a code snippet that informs our users about the permissions the application needs to send SMS. Step 8 shows you how to run the application.
We add the code in step 7 above to inform our users about the permissions our application needs to send SMS. Then at step 6, we add the actual code that sends the SMS message. We use the built-in Android telephony API class called android.telephony.SmsManager. Easy isn't it?
The application uses the built-in Android telephony API class `android.telephony.SmsManager` to send SMS; for more information, see: documentation of SmsManager API.
The complete source code for this application is hosted at Kenai.com. You must have a Subversion client installed on your machine to checkout the project repository.
If you have the command line Subversion client, you can checkout the repository by running:
`svn co https://svn.kenai.com/svn/ron-os-sample-code~project-code-repository/BeginningAndroidProjects/SendingSMS`
This will checkout a copy of the SendingSMS project.
Note: The code snippets in this section are from a modified version of the source code in the SendingSMS project; the full source code is in a separate project called SendingSMS2.
You can checkout the project's repository via the command line Subversion client by running:
`svn co https://svn.kenai.com/svn/ron-os-sample-code~project-code-repository/BeginningAndroidProjects/SendingSMS2`
public void send( android.view.View view) {I've implement a BroadcastReceiver to listen for "SMS_SENT" update:
android.telephony.SmsManager smsManager = android.telephony.SmsManager.getDefault();
android.app.PendingIntent sendingIntent = android.app.PendingIntent.getBroadcast(this, 0,
new android.content.Intent(SMS_SENT), 0);
String addr = recipient.getText().toString();
String text = message.getText().toString();
sendButton.setEnabled(false);
status.setText(R.string.messageSending);
smsManager.sendTextMessage(addr, null, text, sendingIntent, null);
}
private final android.content.BroadcastReceiver smsSentReceiver = new android.content.BroadcastReceiver() {Then I register the BroadcastReceiver in the onStart() method, which is called when the SMSActivity starts:
@Override
public void onReceive(android.content.Context context, android.content.Intent data) {
switch (getResultCode()) {
case RESULT_OK:
status.setText(R.string.messageSentSuccess);
break;
default:
status.setText(R.string.messageSentFailed);
}
recipient.setText("");
message.setText("");
sendButton.setEnabled(true);
}
};
@OverrideThen I unregistered it in the onStop() method, which is called when the SMSActivity stops, to avoid leaks:
protected void onStart() {
super.onStart();
registerReceiver(smsSentReceiver, new android.content.IntentFilter(SMS_SENT));
}
@OverrideAll done! You have now created your first simple and practical Android application =)
protected void onStop() {
super.onStop();
unregisterReceiver(smsSentReceiver);
}
What's Next?
Checkout the complete project @ http://kenai.com/projects/ron-os-sample-code/sources/project-code-repository/history/BeginningAndroidProjects. You must have any Subversion client installed on your machine to checkout my example project.
Checkout the complete project @ http://kenai.com/projects/ron-os-sample-code/sources/project-code-repository/history/BeginningAndroidProjects. You must have any Subversion client installed on your machine to checkout my example project.
Thank You!
Subscribe to:
Posts (Atom)




















