Thursday, January 31, 2008

Opening New Screen in Android

An Android application, at most, contains more than one screen. But, how we can open a new screen after clicking a button, choosing a menu, or other? It is not too difficult to do in Android.

There are a few step to do, to open a new screen in android. You have to create an activity class, an xml layout, update AndroidManifest to know your second/third .. activity class, and put a code to call the new activity / screen.

An Activity class can be created with extending from Activity, ListActivity or other Activity class. Each Activity Class should have an xml layout as a view screen as a representation of the Activity Class.

Android Manifest should be updated to know the new activity / screen. so, when requested to show the new screen, it knows which class to execute.

At last you should put a piece of code to first screen, to show the new screen. Below is an example to open a new screen:

//screen1.java


package test.android;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.widget.Button;

public class Screen1 extends Activity
{
   public void onCreate(Bundle icicle)
   {
      super.onCreate(icicle);
      setContentView(R.layout.screen1);
      Button b = (Button) findViewById(R.id.btnClick);
      b.setOnClickListener(new View.OnClickListener() {
         public void onClick(View arg0) {
         Intent i = new Intent(screen1.this, screen2.class);
         startActivity(i);
         }
      });
   }
}

//screen1.xml


<?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="You are in the first Screen"
/>
<Button
   id ="@+id/btnClick"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Open New Screen"
/>

</LinearLayout>

//screen2.java


package test.android;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;

public class Screen2 extends Activity
{
   public void onCreate(Bundle icicle)
   {
      super.onCreate(icicle);
      setContentView(R.layout.screen2);
      Button b = (Button) findViewById(R.id.btnClick2);
      b.setOnClickListener(new View.OnClickListener() {
         public void onClick(View arg0) {
         setResult(RESULT_OK);
         finish();
         }
      });
   }
}

//screen2.xml

<?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="You are in the New Screen"
/>
<Button
   id ="@+id/btnClick2"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Close"
/>

</LinearLayout>

//AndroidManifest.xml


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="test.android">
   <application android:icon="@drawable/icon">
      <activity class=".Screen1" android:label="Screen 1">
         <intent-filter>
         <action android:value="android.intent.action.MAIN" />
         <category android:value="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
      <activity class=".Screen2" android:label="Screen 2">
      </activity>
   </application>
</manifest>





ok, Have a nice try!

Do you want to learn more ?
Learning with sample code ?
Learning by Doing ?
Just Visit http://learncodes.googlepages.com/
and there is Android UI Design at there.
You can download code almost the same as this at there too


Read More……

Run Android Application from Command Line

Sometime, we want to start the android application program from command line (Android Shell). Before, we usually clicking on the icon at application folder to run our program. So, there is an alternative way to run the program.

We use the Android Shell and issue am command to brought up the program. below is an example to do that.
1. Make sure that android emulator is running
2. Enter the shell with issuing command at command shell (prompt): adb shell
3. Issue am command. am command syntax is as follow :

am [start|instrument]
am start [-a <action>] [-d ] [-t <mime_type>]
[-c <category> [-c <category>] ...]
[-e <extra_key> <extra_value> [-e <extra_key> <extra_value> ...]
[-n <component>] [-D] [<uri>]
am instrument [-e <arg_name> <arg_value>] [-p <prof_file>]
[-w] <component>

for example we have android program with Manifest like below:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.iftitah.android.contact">
  <application android:icon="@drawable/icon">
   <activity class=".Contact" android:label="@string/app_name">
    <intent-filter>
    <action android:value="android.intent.action.MAIN" />
    <category android:value="android.intent.category.LAUNCHER" />
   </intent-filter>
  </activity>
 </application>
.
.
</manifest>

To run the code issue command like this (in one line):

am start -a android.intent.action.MAIN -n
com.iftitah.android.contact/com.iftitah.android.contact.Contact

ok, Have a nice try!

Do you want to learn more ?
Learning with sample code ?
Learning by Doing ?
Just Visit http://learncodes.googlepages.com/
and there is Android UI Design at there.


Read More……

Friday, January 18, 2008

Android Database

Database is important thing in programming. Many of our code always use data to be processed and saved. Just like any other programming environtment, Android support database programming too. You can use default database supported by android, SQLiteDatabase.

Database in SQLiteDatabase can contains more than one table, assume that we have one database PERSONALDB, and have one table BIODATA. The structure of BIODATA is:

_id integer
code string
name string
gender string

_id is for key increment,
code, name, and gender is for description of person.

When program called in the first time, we have to make sure that the database and table opened if it is exist. if not, than we have to create the database and tabel. As an example from Android notepad sample, here the class PersonDbHelper for manipulating table Biodata.

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class PersonDbHelper {
    class Row extends Object {
        public long _Id;
        public String code;
        public String name;
        public String gender;
    }

    private static final String DATABASE_CREATE =
        "create table BIODATA(_id integer primary key autoincrement, "
            + "code text not null,"
            + "name text not null"
            +");";

    private static final String DATABASE_NAME = "PERSONALDB";

    private static final String DATABASE_TABLE = "BIODATA";

    private static final int DATABASE_VERSION = 1;

    private SQLiteDatabase db;

    public PersonDbHelper(Context ctx) {
        try {
            db = ctx.openDatabase(DATABASE_NAME, null);
        } catch (FileNotFoundException e) {
            try {
                db =
                    ctx.createDatabase(DATABASE_NAME, DATABASE_VERSION, 0,
                        null);
                db.execSQL(DATABASE_CREATE);
            } catch (FileNotFoundException e1) {
                db = null;
            }
        }
    }

    public void close() {
        db.close();
    }

    public void createRow(String code, String name) {
        ContentValues initialValues = new ContentValues();
        initialValues.put("code", code);
        initialValues.put("name", name);
        db.insert(DATABASE_TABLE, null, initialValues);
    }

    public void deleteRow(long rowId) {
        db.delete(DATABASE_TABLE, "_id=" + rowId, null);
    }

    public List<Row> fetchAllRows() {
        ArrayList<Row> ret = new ArrayList<Row>();
        try {
            Cursor c =
                db.query(DATABASE_TABLE, new String[] {
                    "_id", "code", "name"}, null, null, null, null, null);
            int numRows = c.count();
            c.first();
            for (int i = 0; i < numRows; ++i) {
                Row row = new Row();
                row._Id = c.getLong(0);
                row.code = c.getString(1);
                row.name = c.getString(2);
                ret.add(row);
                c.next();
            }
        } catch (SQLException e) {
            Log.e("Exception on query", e.toString());
        }
        return ret;
    }

    public Row fetchRow(long rowId) {
        Row row = new Row();
        Cursor c =
            db.query(true, DATABASE_TABLE, new String[] {
                "_id", "code", "name"}, "_id=" + rowId, null, null,
                null, null);
        if (c.count() > 0) {
            c.first();
            row._Id = c.getLong(0);
            row.code = c.getString(1);
            row.name = c.getString(2);
            return row;
        } else {
            row.rowId = -1;
            row.code = row.name= null;
        }
        return row;
    }

    public void updateRow(long rowId, String code, String name) {
        ContentValues args = new ContentValues();
        args.put("code", code);
        args.put("name", name);
        db.update(DATABASE_TABLE, args, "_id=" + rowId, null);
    }
    public Cursor GetAllRows() {
        try {
            return db.query(DATABASE_TABLE, new String[] {
                    "_id", "code", "name"}, null, null, null, null, null);
        } catch (SQLException e) {
            Log.e("Exception on query", e.toString());
            return null;
        }
    }
}

in Method onCreate Activity you just put single command below to initialize the database :
...
Db = new PersonDbHelper(this);
...

it will try opening PersonalDB first, if it is not exist, than it will create the database. in this PersonDbHelper class, you have method for inserting, deleting, updating, querying table.

Ok, have a nice try

Do you want to learn more ?
Learning with sample code ?
Learning by Doing ?
Just Visit http://learncodes.googlepages.com/
and there is Android UI Design at there.


Read More……

Tuesday, January 15, 2008

Layouting Component Choices

Component Arrangement on Android is simple and we have more than one way to make the same design screen. we can use RelativeLayout, LinearLayout, or other layout. And we can combine two or more layout into one design screen.

For example, we want to desain screen as the image below:


The design screen can be expressed as 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 id="@+id/objLbl1"
android:layout_width="80sp"
android:layout_height="24sp"
android:text="Code"
/>
<EditText id="@+id/objTxt1"
android:layout_width="134sp"
android:layout_height="24sp"
android:layout_alignTop="@id/objLbl1"
android:layout_toRight="@id/objLbl1"
android:text="Edit 1"
android:singleLine="True"
/>
<TextView id="@+id/objLbl2"
android:layout_width="80sp"
android:layout_height="24sp"
android:layout_below="@id/objTxt1"
android:text="Name"
/>
<EditText id="@+id/objTxt2"
android:layout_width="134sp"
android:layout_height="24sp"
android:layout_alignTop="@id/objLbl2"
android:layout_below="@id/objTxt1"
android:layout_toRight="@id/objLbl1"
android:text="Edit 2"
android:singleLine="True"
/>
<Button id="@+id/objBtn1"
android:layout_width="80sp"
android:layout_height="24sp"
android:layout_below="@id/objTxt2"
android:text="Save"
/>
</RelativeLayout>

Or, your can replace with xml 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="fill_parent"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<TextView id="@+id/objLbl1"
android:layout_width="80sp"
android:layout_height="24sp"
android:text="Code"
/>
<EditText id="@+id/objTxt1"
android:layout_width="134sp"
android:layout_height="24sp"
android:text="Edit 1"
android:singleLine="True"
/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<TextView id="@+id/objLbl2"
android:layout_width="80sp"
android:layout_height="24sp"
android:layout_below="@id/objTxt1"
android:text="Name"
/>
<EditText id="@+id/objTxt2"
android:layout_width="134sp"
android:layout_height="24sp"
android:text="Edit 2"
android:singleLine="True"
/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>

<Button id="@+id/objBtn1"
android:layout_width="80sp"
android:layout_height="24sp"
android:text="Save"
/>
</LinearLayout>
</LinearLayout>

Ok, have a nice try!

Do you want to learn more ?
Learning with sample code ?
Learning by Doing ?
Just Visit http://learncodes.googlepages.com/
and there is Android UI Design at there.


Read More……

Monday, January 14, 2008

Viewing Android Debugging Log

When our application is installed on android emulator, we run it and expect it will running successfully. But, sometimes it is unsuccessfully, an error message appears, sometimes, likely it is not from our application, so how to know which part of our codes is currently throwing the error..

An alternative way is to watch the log produced by the emulator. Just run the emulator, wait until completed, then from shell, issue command:

adb logcat

The log will be show up at a new windows, and you can watch which part of your codes currently throwing error.











ok, have a nice try!


Read More……

Accessing Android Shell

Frequently, we want to know where the code placed inside android. we can know it with entering the Android Emulator shell. Just run the Emulator and wait it runs completely, issue command to access shell, then we will be inside the Emulator shell.

Here the command to access Shell :

adb shell

then we will promptly with
#

it is linux shell command, and we can issue command just like in Linux environtment, with some limitation.

Application installed in emulator will reside at /data/app/ directory, and database(s) create by the app will reside at /data/data/<package name>/databases/

Ok, have a nice try!


Read More……

Resize Android EditText in XML

Someday, we want to set size Android Component in our application. We have many ways to set and reset the size of component. In this example we deal with Android EditText.

The Size of Component in Android can be set in XML with providing property android:layout_width and android:layout_height with a value followed by unit. For example we want to set EditText with 200sp width and 24sp height, the declaration is as follow:

<EditText id="@+id/Text1"
android:layout_width="200sp"
android:layout_height="24sp"
android:text="Text1"
android:singleLine="True"
/>

For detail information on unit like "sp", "pt", you can browse at Android Documentation or in topic Creating User Interface

Ok, Good Luck!


Read More……

Saturday, January 12, 2008

SMS Emulation on Android

When we are trying to test SMS based program on Android, we have to simulate receiving SMS. Fortunately, with new SDK, we can simulate the SMS come to Emulator. We have just to connect to emulator using telnet and there we can emulate the SMS. Below step by step to emulate the SMS:
  • Start the emulator, you free to give the option, For example just type emulator on shell prompt
  • Open a new shell and type :

    adb devices

    to know the port emulator used. The console of the first emulator instance running on a given machine uses 5554 port, The command above just to make sure which port the instance used.
  • Connect to the console using telnet command like:
    telnet localhost 5554
  • After you have come to the shell you can emulate sms with command:

    sms send <phonesender> <text message>
Ok, Good luck with your try, and Hope, One of Use will win the Android Google Challenge!


Read More……

Monday, January 7, 2008

Android User Interface Designer (2)

Android User Interface Designer that i 've write before has been released. You can download and try it. This code can be download at SourceForge.Net and can be download and Files.
Just Try it and enjoy it!


Read More……

Wednesday, January 2, 2008

Android User Interface Designer

Just want to design User Interface easily, I have created Android User Interface Designer. In the first version, I have included Label, EditText, and Button Object. Later, Other object will be included. Other Object will be included in the next version.

Each Object packed with minimal property, and layout with RelativeLayout. Just to make it easy for beginner, and to simplify coding. The next version will include more property.

Layout used in this version is RelativeLayout with its hight and width specified as "fill_parent". That means, this layout will covers all screen.

Each Object packed with attribute: height, width in ps, and text. MultiLine specified for EditText only.

If you are interested on trying this program, please see on http://files.pemikiran.com whenever it is ready to download. And I plan to publish the tool at Sourceforge.Net.


Read More……

Creating User interface

User interface in Android Platform just like other Java based user interface in common. We can create User Interface from the scratch with Java code, or Using XML that come with Android. Everytime we create Android Project whether from command line using ActivityCreator or Using Android Plugins on Eclipse we have some directory result. One of them is res directory. Res directory contains layout and value subdirectory. The XML that govern the User Interface located in these subdirectories at most.

Some Definition about the layout we place at layout subdirectory, the value refers in the layout placed in value subdirectory. let's start with the main.xml located in layout directory. Main.xml contains main definition of layout. below sample of main.xml

<?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 id="@+id/objLbl1"
android:layout_width="134sp"
android:layout_height="80sp"
android:text="Label 1"
/>
<EditText id="@+id/objTxt1"
android:layout_width="134sp"
android:layout_height="134sp"
android:layout_alignTop="@id/objLbl1"
android:layout_toRight="@id/objLbl1"
android:text=""
/>
<Button id="@+id/objBtn1"
android:layout_width="134sp"
android:layout_height="24sp"
android:layout_below="@id/objTxt1"
android:layout_toRight="@id/objLbl1"
android:text="Btn 1"
/>
</RelativeLayout>

RelativeLayout is a layout with each object inside is placed relative to others. Maybe below, right, align top, align bottom to other object. There are many Layout but we study this first. There are 3 attributes at least, to define this layout, xmlns:android, android:layout_width and android:layout_height.

xmlns:android is for identification that this xml is used for android, not for other function, android:layout_width and android:layout_height is to specify the dimension. it can be fill_parent, wrap_content, or just spesify the dimension with number followed by unit of measurement.

Unit of measurement supported by android (from the documentation) can be :

px
Pixels - corresponds to actual pixels on the screen.

in
Inches - based on the physical size of the screen.

mm
Millimeters - based on the physical size of the screen.

pt
Points - 1/72 of an inch based on the physical size of the screen.

dp
Density-independent Pixels - an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ration of dp-to-pixel will change with the screen density, but not necessarily directly; instead the ratio is selected is something that is close to the screen.

sp
Scale-independent Pixels - this is like the dp unit, but it is also scaled by the user's font size preference. It is recommend you use this unit when specifying font sizes, so they will be adjusted for both the screen density and user's preference.

There are many object that can be created. but we focus on Label, EditText, And Button, because these three objects is used frequently.

Label is declared with tag <TextView />. Some attributes can be set to this object, but we can just used id, the dimension, text attribute, and relative position to others like align with other, right from other, and below from other. Id is used to identify this label. In this example, Label is placed first, so others will refer it with its id

EditText is declared with tag <EditText />. Attributes used in this example is just like label but with position relative to the label. Its relative position is to the right from label.

Button is declared with tag <Button />. Attributes used in this example is just like edittext but with position relative to edittext and label. Its relative position is below from the edittext and right after label.


Read More……