• SEARCH BOX

Combine Jetty and Spring Application Context

Spring's Logo The goal of this post is to use one xml configuration file which is Spring's applicationContext.xml and load it only once for the duration of the application running in an embedded jetty server. Read more...

Tutorial on Android Layout

A thumbnail of adroid. Android is an open source platform for mobile devices. Not a hardware. It is a software stack as defined by Google. Encase your not familiar with the term, software stack is compose of an Operating System(OS), middle-ware and the key applications. Read more...

Hi, my name's Paul Labis.

I'm a developer in Makati City, Philippines. Focused on building online Java/J2EE based applications. I'm interested in freelance or part-time work from home.

Sunday, March 28, 2010

Tutorial on Android Layout

On my previous article, I've discussed more on the theory and definition of an Android. In this article, we will be dealing more on the technical aspect of developing android application layout. I will walk you through various elements that make up the user interface(UI) and how to position different widgets on an android screen.

Terms to remember:
  • Activity - the basic unit of an android application. It contains views and ViewGroup. 
  • View - a widget that has an appearance on screen.
  • Widget - are user interface components like buttons, labels, text boxes, etc.
  • ViewGroup - a special type of View that provides the layout in which you can group views, order the appearance and sequence your views.
Just an additional information; In a typical android project, UI is defined using an XML file located in the res/layout folder. An example is main.xml located in res/layout folder.  During runtime, the .xml file where you defined your UI is loaded using the onCreate() event handler of your activity class and using setContentView() method of the extended Activity class. Moreover, during compilation time, each of the element in the defined UI xml file are compiled into an equivalent Android GUI class wherein its attributes are represented by methods.


Furthermore, Android supports various ViewGroups and among those are the linear, absolute, table, relative and scroll view layouts. This layouts will be discussed in details below.

At this point, I presume you already setup your development environment for programming Android applications. If you haven't, please follow the android setup tutorial.

Get Your Hands Dirty
So, lets begin by creating the sample project on eclipse. Do observe the screen shot below. (Click the image to enlarge)

There is another application called DroidDraw which you can use to design your layout aside from eclipse. Though, eclipse has its Android layout editor, it has limited features. Perhaps, you might want to use DroidDraw instead which supports drag and drop. However, its on your disposal whether which tool could help. On this ongoing tutorial, we will be using only the xml editor on eclipse.

LinearLayout 
It is the layout widget where you are able to arrange your views horizontally or vertically on a single row or single column. To see the how it works, lets create linear.xml under res/layout folder in the project and enter the code below:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<TextView
android:id="@+id/sampleText01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sample Text 01"
/>

<TextView
android:id="@+id/sampleText02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sample Text 02"
/>

</LinearLayout>
and change the LayoutPractice.java code to:
package com.techie.layout;

import android.app.Activity;
import android.os.Bundle;

public class LayoutPractice extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.linear);
}
}
that will result to:
On the code above, you'll notice that it starts with a container <LinearLayout> android xml element that hold and control the order and appearance of the other views elements inside it. That serves as the main container of the views elements <TextView>. You'll also notice that we specified the layouts' orientation to vertical. By its default, it is set to horizontal. Other than that, we also specified the layouts' width and height. That basically are the basic ones that you need to specify in a layout element.

The fill_parent and wrap_content are two constants. You should use fill_parent if you want the full size of the parent container which in our case is the linear layout container. Use wrap_content if you want the size of its content. Try adding a button to linear.xml and specify its width like below:
<Button
          android:id="@+id/sampleButton01"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:text="Sample Button 01"
          />
Experiment by changing its width to wrap_content. Also, you can specify its layouts width and size by pixel(px). See the code below for an example:
<Button
          android:id="@+id/sampleButton01"
          android:layout_width="150px"
          android:layout_height="40px"
          android:text="Sample Button 01"
          /> 

In linear layout, layout_weight and layout_gravity attributes are applicable to views contained within it.  Below is an example of how to use it.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical">
 
    <TextView
          android:id="@+id/sampleText01"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="Sample Text 01"   
          />
         
    <TextView
          android:id="@+id/sampleText02"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="Sample Text 02"
          />
         
      <Button
          android:id="@+id/sampleButton01"
          android:layout_width="150px"
          android:layout_height="40px"
          android:text="Sample Button 01"
          />
  <Button
          android:id="@+id/sampleButton02"
          android:layout_width="150px"
          android:layout_height="40px"
          android:text="Sample Button 02"
          android:layout_weight="0.2"
          android:layout_gravity="right"
          />
  <Button
          android:id="@+id/sampleButton03"
          android:layout_width="150px"
          android:layout_height="40px"
          android:text="Sample Button 03"
          android:layout_weight="0.2"
          android:layout_gravity="left"
          />
  <EditText      
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"       
        android:textSize="18sp"
        android:layout_weight="0.8"       
        />
 
</LinearLayout>


In the above code, we applied layout_gravity to both buttons which aligned them to right and left corner of the parent container. The layout_weight attribute was used to specify the ratio in which the button and editText views occupy the remaining space on the screen.
AbsoluteLayout 
It enables you to specify the exact location of its content views like buttons, textview, and etc.. Lets create another android xml named absolute.xml under res/layout folder of the project. See the code below.
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <Button
        android:layout_width="150px"
        android:layout_height="wrap_content"
        android:text="Button 1"
        android:layout_x="12px"
        android:layout_y="361px"
        />
    <Button
        android:layout_width="150px"
        android:layout_height="wrap_content"
        android:text="Button 2"
        android:layout_x="160px"
        android:layout_y="361px"
        />
</AbsoluteLayout>

So, in the above you'll notice that we make use of the view attributes layout_x and layout_y to specify the exact positions of the absolute layouts' contents. To be able to see the changes, do change the code below:
package com.techie.layout;

import android.app.Activity;
import android.os.Bundle;

public class LayoutPractice extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.absolute);
    }
}
It will render the user interface like this:
TableLayout
Like a  normal table tag, it enables you to group views by rows and columns. Every views you place inside a row forms a cell. The cells' width is determined by the largest cell by that column. 


Create table.xml under res/layout of the project folder containing the following code:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
 
  <TableRow>
          <TextView
            android:text="First Name"             
              />
          <EditText
              android:layout_width="150px"
              />
  </TableRow>
 
  <TableRow>
          <TextView
            android:text="Last Name"             
              />
          <EditText
              android:layout_width="150px"
              />
  </TableRow>
 
  <TableRow>
          <TextView
            android:text="Are you developer?"             
              />
          <CheckBox
              android:text="Yes"
              />
  </TableRow>

  <TableRow>
          <TextView
            android:text="Password"             
              />
          <EditText
              android:layout_width="150px"
              android:password="true"
              />
  </TableRow>
 
  <TableRow>
          <TextView/>
          <Button
              android:text="Submit"
              />
  </TableRow>
 
</TableLayout>


Don't forget to update the LayoutPractice activity code to
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.table);
    }

So, as you can see above, the code implemented 2 column and 5 rows. The  views width  on column 1 were of same size with the largest view width in that column. Note also that  a view  was added just above the Submit button so that the Submit button will align on the second column. If you remove the textView, it will look like this:
Moreover, on the 5th row, a textView for password was added. The attribute password was set to true so that the text entered will be replaced with a dot.


RelativeLayout

This layout enables you to specify child view's position relating to another view. It makes use of available view attributes alignParentTop, alignParentLeft, alignLeft, alighRight, below, centerHorizontal and etc. Those mentioned attributes are made available to views inside a relative layout for them to be align relative to another view. Take note that it utilize id's of another view. Take a look at 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">
 
   <TextView
        android:id="@+id/labelComments"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Comments"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        />
    <EditText
        android:id="@+id/textComments"
        android:layout_width="fill_parent"
        android:layout_height="170px"
        android:textSize="18sp"
        android:layout_alignLeft="@+id/labelComments"
        android:layout_below="@+id/labelComments"
        android:layout_centerHorizontal="true"
        />
    <Button
        android:id="@+id/buttonSave"
        android:layout_width="125px"
        android:layout_height="wrap_content"
        android:text="Save"
        android:layout_below="@+id/textComments"
        android:layout_alignRight="@+id/textComments"
        />
    <Button
        android:id="@+id/buttonCancel"
        android:layout_width="124px"
        android:layout_height="wrap_content"
        android:text="Cancel"
        android:layout_below="@+id/textComments"
        android:layout_alignLeft="@+id/textComments"
        />
 
</RelativeLayout>


ScrollView

It is a frame layout that enables a feature where the user can scroll through a list that basically occupy more space than the available physical space on your android phone. A scrollview can only contain one viewgroup which is normally a linearlayout. The code below has a linear layout inside a scroll view. 

Try this by creating scrollview.xml under res/layout folder of the project.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    android:id="@+id/widget54"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <LinearLayout
        android:layout_width="300px"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >
        <Button
            android:id="@+id/button1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Button 1"
            />
        <Button
            android:id="@+id/button2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Button 2"
            />
        <Button
            android:id="@+id/button3"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Button 3"
            />
        <EditText
            android:id="@+id/txt1"
            android:layout_width="fill_parent"
            android:layout_height="300px"
            />
        <Button
            android:id="@+id/button4"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Button 4"
            />
        <Button
            android:id="@+id/button5"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Button 5"
            />
        <EditText
            android:id="@+id/txt2"
            android:layout_width="fill_parent"
            android:layout_height="200px"
            />
    </LinearLayout>
</ScrollView>

The above code results to the following:

The above is a neat implementation of scroll view where inside is a linear container having contents that occupy more than the available actual space of an android screen.


Nutshell
In this article, you saw various layout implementations with wigets on top of Android. On the next articles, we will focus on other components of the UI which is the views.  Practice on your newly learned lay-outing skill. So, stay tune and have fun with android! 

I would like to give credit to Wei-Meng Lee who written  a very helpful tutorial on android layout.

Thursday, March 25, 2010

Learning Android By Definition

Android is an open source platform for mobile devices. It is not a hardware. Its basically a software. In fact, It is a software stack as defined by Google. Encase your not familiar with the term, software stack is compose of an Operating System(OS), middle-ware & the key applications.
  • OS is by simply defined as platform between you and the hardware and where all applications run.
  • Middle-ware is/are the components and available package that allows applications to communicate to a network and to one another.
  • Key Applications is/are the actual programs or software that the phones will run
It was the product of the joint effort of Google and Open Handset Alliance(OHA). It was released November 5, 2007 which is shortly just after Apple's first generation iPhone release. Android is based on an opensource operating system called Linux.

Android is equipped with a set of core applications that includes an email client, SMS program, browser, contacts, calendar, maps, and others. Another good thing is that all applications are written using the Java programming language which is also an opensource programming language. See below for features.

Features

  • Application framework enabling reuse and replacement of components
  • Dalvik virtual machine optimized for mobile devices
  • Integrated browser based on the open source WebKit engine
  • Optimized graphics powered by a custom 2D graphics library; 3D graphics based on the OpenGL ES 1.0 specification (hardware acceleration optional)
  • SQLite for structured data storage
  • Media support for common audio, video, and still image formats (MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, GIF)
  • GSM Telephony (hardware dependent)
  • Bluetooth, EDGE, 3G, and WiFi (hardware dependent)
  • Camera, GPS, compass, and accelerometer (hardware dependent)
  • Rich development environment including a device emulator, tools for debugging, memory and performance profiling, and a plugin for the Eclipse ID
Android is an exiting open platform for mobile development. It offer's the ability to build extremely rich and innovative applications. Developers are given freedom to take full advantage of the device hardware, retrieve location information, run silent operations, camera usage, alerts, and much, much more. Finally, the Application Program Interface(API ) is freely and fully accessible for developers. That makes learning so much easier.

Market demand for android software and developers are increasing. No wonder my company,  Orange & Bronze Software Labs, Inc., was encouraging its developers to start learning, mastering and creating software/applications made in Java that runs in an Android phone.

I just started with Android couple of days ago and so far, I find it very interesting & fun to learn. So, I recommend you get started too. Good luck!

Note: To be able to learn more about Android, visit http://developer.android.com/.

Tuesday, March 23, 2010

Hello World by Techie Boy

This is my first article post so its a Hello World article! Its hello world because most of developers do the very first application regardless of any technology that is being use, they begin by displaying a "hello world" on a computer screen or may vary with regards to its intention.

Moving forward, I'm Paul Labis. Sole writer & owner of this blog. I am a graduate of the degree in Information Management from Ateneo de Cagayan University and working as a Software Engineer in Orange & Bronze Software Labs. 

I like anything related to information technology. I am also an Open Source believer. That sums up my explanation why I am inclined to Java programming, Groovy & Grails, App Engine, Python & DJango and other Open Source Frameworks.

You might be interested a bit on the reason why do I blog. Well, I'd say its primarily because I wanted to contribute and share my knowledge to everyone else who might need a hand. At first, my motivation was money but it was not enough and so for a while, I stopped blogging. Until such time and out off boredom, I reflected on a tutorial written by IBM about the groovy scripting language. I was able to reflect that if it wasn't because of this tutorial, I would not have accomplish my task. So I was deeply thinking and prospered on my decision that if I have an idle time, I'd spent it on making articles that would help other people do their task while at the same time enjoying and learning the new stuff.

I know that there are a lot of good writers on-line publishing much relevant articles as I may have, but here is a thing, I don't care... Yes! I don't really care... I know am a horrible writer though. But, whatever that is your thinking, practice results to improvement and everyone knows that..

I hope you'll enjoy my blog articles and good luck. If you have relevant concerns, please feel free to drop an email at paullabis@gmail.com.

Monday, March 22, 2010

Web Service Tutorial in Java

Web Service is a piece of software that makes a service available on web. It uses a universal standard XML processing. It is interoperable in a sense that it enables a .NET software on a Windows Server to communicate to a JAVA software on a Unix. In other words, its not bound to a specific programming language or an operating system.
  • "Provider agent" implements a Web service
  • "Requester agent" (a.k.a. "client") makes use of that Web service
  • WSD(Web Service Description) represents a "contract"
  • Specifies the message formats, transport protocols, locations 
What we want to do in this article is to create a project where it utilizes a web service online. I plot the step by step way of utilizing a web service through terminal.


Please note that before you start the tutorial, you should make sure that you already setup Java on your ubuntu or linux operating system. Throughout this tutorial, we are not going to use eclipse or any IDE to acomplish our objective of utilizing a remote web service.

1. Find a Remote Web Service/ Webservice

There are a lot of sample remote web services to play on in www.webservicex.net. For the purpose of this tutorial. I would like to utilize Translator Engine Web Service (http://www.webservicex.net/WCF/ServiceDetails.aspx?SID=47). We are going to use wsimport to generates portable JAX-WS artifacts for invoking a web service.

2. Create a dynamic proxy from WSDL(Web Service Description Language)

We will make it structural by creating a directory : ./TranslatorWS
Run generator on terminal by either $JAVA_HOME/Commands or $JAVA_HOME/bin/wsimport URL
In our case that is:
$ /usr/lib/jvm/java-6-sun-1.6.0.16/bin/wsimport -d ./TranslatorWS http://www.webservicex.net/TranslateService.asmx?wsdl
Result: It will generate bunch of .class files under ./TranslatorWS folder

3. Generate a jar file from the generated .class files

Open a terminal and navigate to your project.
Run on terminal:
$ jar cvf TranslatorWS.jar -C ./TranslatorWS/ .
Result: A jar file name TranslatorWS.jar is generated out of the dynamic proxy of the remote Web Service.

4. Write Client code

 Let's structure our code by creating ./src folder and write something like com.client.TranslatorWSClient.java


(Note: Inside src is com folder. Inside com is client folder. Inside client folder is the Java class)
Result: You are able to create the code to utilized the web service.




package com.client;

import net.webservicex.Translate;
import net.webservicex.TranslateService;
import net.webservicex.TranslateServiceSoap;

public class TranslatorWS {
/**
* * @param args
* */
public static void main(String[] args) {
if (args.equals(null) || args.length == 0){
printHelp();
}

TranslateServiceSoap translatorService = new TranslateService().getTranslateServiceSoap();
if ("EnglishTOFrench".equals(args[0])){
System.out.println("Translation:");
System.out.println(translatorService.translate(args[0], args[1]));
}
}
private static void printHelp() {
System.out.println("TranslatorWS <language> <Word To Translate>");
}
}


5. Compile Client Code

Create a directory ./bin where you will store your compiled .class client class.
RUN on terminal:
$ javac -classpath ./TranslatorWS.jar -d ./bin/ -verbose ./src/com/client/TranslatorWS.java
Result : compiled client code under ./bin directory.

6. Run the client to utilize remote web service

Run on Terminal:
$ java -classpath ./bin/:./TranslatorWS.jar com.client.TranslatorWS EnglishTOFrench goodTranslation:
Error occured when translating text please contact support@webservicex.net
Result: A translation of the word. However, on this web service, an error message is sent back instead of the real thing.


NOTE: These are free Web services just made for practice or tutorials therefore they are unreliable, sometimes their response time is quite big and wrong.
 

Author

Followers

Techie Projects

Open Source