Monday, 11 June 2012

Creating a small Calculater

.Small Calculator:-
We try to making a simple calculator.In which we take two number and do some kind of addition,subtraction operation.
Before doing Android application we must take consider the layout issue


Layout of Simple Calculator









Layout issue
(1)A TextView that would be a Label i.e.Simple Calculator
(2)A Line which separate the Label and EditText
(2)A EditText in which number and result will be shown.
(3)A List of Button  from 0 to 9 with additional button + , - ,Enter and Clear button

Select the build target








































In my previous post I take the Android 4.03 target machine.Here we take Android 1.5. This is compatible with Android 1.6, Android 2.0, Android 2.1, Android 2.2 , Android 2,3 and Android 3.0 version.
Small Calculator Android Project

This is a new simple calculator Android Project.
main.xml

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tableLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/tv1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/cal"
        android:textSize="32dp"       
        android:background="@color/colu"
                       
        />
     <View

        android:layout_height="6dip"
        android:background="#FF0000" />

     <EditText
         android:id="@+id/edtext"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_marginTop="10dip"
       

      />
      <TableRow

        android:id="@+id/Row1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5dip" >
    
     <Button
        android:id="@+id/one"
        android:textSize="30dp" 
        android:background="@drawable/but_img"    
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:text="1"
      
       />
       <Button
        android:id="@+id/two"
        android:textSize="30dp" 
        android:background="@drawable/but_img"    
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginLeft="60dip"
        android:text="2"
       />
      
       <Button
        android:id="@+id/three"
        android:textSize="30dp" 
        android:background="@drawable/but_img"    
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginLeft="60dip"
        android:text="3"
       />
       </TableRow>
      
       <TableRow

         android:id="@+id/Row2"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:padding="5dip">
      
        <Button
        android:id="@+id/four"
        android:textSize="30dp" 
        android:background="@drawable/but_img"    
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:text="4"

       />
      
          <Button

        android:id="@+id/five"
        android:textSize="30dp" 
        android:background="@drawable/but_img"    
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginLeft="60dip"
        android:text="5"

       />
      
         
          <Button

        android:id="@+id/six"
        android:textSize="30dp" 
        android:background="@drawable/but_img"    
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginLeft="60dip"
        android:text="6"

       />       
         
        </TableRow>
       
      
        <TableRow

         android:id="@+id/Row3"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:padding="5dip">

      
        <Button
        android:id="@+id/seven"
        android:textSize="30dp" 
        android:background="@drawable/but_img"    
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:text="7"

       />
      
          <Button

        android:id="@+id/eight"
        android:textSize="30dp" 
        android:background="@drawable/but_img"    
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginLeft="60dip"
        android:text="8"

       />
      
         
          <Button

        android:id="@+id/nine"
        android:textSize="30dp" 
        android:background="@drawable/but_img"    
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginLeft="60dip"
        android:text="9"

       />       
         
        </TableRow>
       
       <TableRow

         android:id="@+id/Row4"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:padding="5dip">

      
        <Button
        android:id="@+id/zero"
        android:textSize="30dp" 
        android:background="@drawable/but_img"    
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:text="0"

       />
      
          <Button

        android:id="@+id/plus"
        android:textSize="30dp" 
        android:background="@drawable/but_img"    
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginLeft="60dip"
        android:text="+"

       />
      
         
          <Button

        android:id="@+id/minus"
        android:textSize="30dp" 
        android:background="@drawable/but_img"    
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginLeft="60dip"
        android:text="-"

       />       
         
        </TableRow>

       
      
       <TableRow
         android:id="@+id/Row5"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:padding="5dip">
      

        <Button
        android:id="@+id/enter"
        android:textSize="18dp" 
        android:background="@drawable/but_img"    
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:text="Enter"

       />
      
          <Button

        android:id="@+id/clear"
        android:textSize="18dp" 
        android:background="@drawable/but_img"    
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginLeft="60dip"
        android:text="Clear"

       />       
         
        </TableRow>

Explanation: if you see carefully the layout of the calculator you will observe that it is structure of combination of row and column
  There are number of layout in available in android.Here we not discuss all. we discuss only In my next coming post I discuss all category of layout.

TableLayout:--The children  under TableLayout are ROW and COLUMN.  but it has no border of their children .A table can leave cells empty.Our all designing layout under the TableLayout.

TableRow:   Each TableRow define a row in table , each row may have zero or more view or cell, each cell or view may define any other kind of view (Button,EditText,TextView,ImageView etc) or viewGroup ie a another TableLayout.     


TextView:   If you see carefully the Label "Simple Calculator" .What it show? It has big size font and backgroundColor.
                 

android:textSize="32dp"       
The textSize is 32dp The number of pixels within a specific area of the screen.it is referred as as dpi (dots per inch).ie  1 dp equals 1.5 physical pixels.






  android:background="@color/colu"  you are seeing in above figure that we make color resources in string.xml since color is also is a kind of resocuces
<string name="cal">Simple Calculator</string> Here we define label on TextView in form of String resource i.e you have to define the color in string.xml file as above

View:-  We draw a single line which demarcate the  EditText and label.it has 6dip width android:layout_height="6dip"and the backgroud color is specified android:background="#FF0000"

     
EditText :-  
android:id="@+id/edtext" It is id (edtext) tag used in Java Source Code.
android:layout_marginTop="10dip" maginTop from Top is 10dip      

TableRow :-   android:id="@+id/Row1" Here is each Row has id attribute
                    android:padding="5dip The View under Row has 5padding space around


Button :-  android:background="@drawable/but_img"  I used button image 50*50 pixel which is stored in /res/drawable/but_img it is in png format but you will never  mention the extension name in android:background="@drawable/but_img" There is no need to specify the full path /res/drawable/but_img in above code since when @ character is specifies it  is understood that it must be in resource folder.The below is mention the how much width and height of but_img.           
        android:layout_width="50dp"
       android:layout_height="50dp"
       android:layout_marginLeft="60dip" android:layout_marginLeft=60dip it is distance between two button.
 Java Source Coding:-



package abh.lay.com;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class LayoutActivity extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
 
    private EditText edtxt;
    private String inital_str="0";
    private String end= "  ";
    private int res=0;
  
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        edtxt = (EditText)findViewById(R.id.edtext);
        edtxt.setText("0");
      
       ((Button)findViewById(R.id.one)).setOnClickListener(this);
       ((Button)findViewById(R.id.two)).setOnClickListener(this);
       ((Button)findViewById(R.id.three)).setOnClickListener(this);
       ((Button)findViewById(R.id.four)).setOnClickListener(this);
       ((Button)findViewById(R.id.five)).setOnClickListener(this);
       ((Button)findViewById(R.id.six)).setOnClickListener(this);
       ((Button)findViewById(R.id.seven)).setOnClickListener(this);
       ((Button)findViewById(R.id.eight)).setOnClickListener(this);
       ((Button)findViewById(R.id.nine)).setOnClickListener(this);
       ((Button)findViewById(R.id.zero)).setOnClickListener(this);
       ((Button)findViewById(R.id.plus)).setOnClickListener(this);
       ((Button)findViewById(R.id.minus)).setOnClickListener(this);
       ((Button)findViewById(R.id.enter)).setOnClickListener(this);
       ((Button)findViewById(R.id.clear)).setOnClickListener(this);
    
    }

    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        // Number buttons: '0' to '9'
        case R.id.one:
        case R.id.two:
        case R.id.three:
        case R.id.four:
        case R.id.five:
        case R.id.six:
        case R.id.seven:
        case R.id.eight:
        case R.id.nine:
        case R.id.zero:
            String lab_num= ((Button)v).getText().toString();
            if(lab_num.equals("0")){inital_str=lab_num;}
            else {inital_str = inital_str+lab_num;}
            edtxt.setText(inital_str);  
            break;
        case R.id.plus:
           calculate();
            end = "+";
            break;
         case R.id.minus:
             calculate();
            end = "-";
            break;
       
         case R.id.enter:
             calculate();
            end = "Enter";
            break;
 
         // Clear button
         case R.id.clear: 
            res = 0;
            inital_str = "0";
            end = " ";
            edtxt.setText("0");
            break;
        }
      }
        private void  calculate() {
              int inNum = Integer.parseInt(inital_str);
              inital_str= "0";
              if (end == " ") {
                 res = inNum;
              } else if (end == "+") {
                 res += inNum;
              } else if (end == "-") {
                 res -= inNum;
              }
               else if (end == "Enter") {
                 // Keep the result for the next operation
              }
              edtxt.setText(String.valueOf(res));
           }
        }


Explanation:

      
P4WSGRJ95N7E

Saturday, 9 June 2012

Using Control in Android program

 Before describing the user control.I told you about  View in my previous positioning.The android.view.View is our base class for user interface.There are three type of view:
  1. SurfaceView
  2. ViewGroup
  3. Widget

The most basic view is SurfaceView. Here we will not discuss this SurfaceView. because it is concern the drawing issue.
ViewGroup is layout concern and contain other view
Widget it is UI component which most often used.
     Widget is part of android.widget package e.g. ListView,Spinner etc.
We start from Button control.
Button Control example:-
In this example we make Edittext and TextView and a button
Step 1: Layout consideration :
       We have two choice to make Layout consideration
(a)Graphical Method
(b)By main.xml file


we take buttonexamplea1 as new project.


Graphical Method: you are seeing the two tab Graphical Layout and main.xml. we click in Graphical Layout.In Graphical we drag a EditText (abh shown in left tab) under TextFields and drop in layout screen.we also drag button and TextView from Form Widget(in left tab)

 When you are designing the layout through Geometrical Method, automatically main.xml file is coded.
   Now we have to  hard coding  in main.xml file
Method 2:-
Line 1:<?xml version="1.0" encoding="utf-8"?>

Line 2:<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
Line 3: android:layout_width="fill_parent"
Line 4: android:layout_height="fill_parent"
Line 5: android:orientation="vertical" > 
Line 6: <EditText  
Line 7: android:id="@+id/mytext"
Line 8: android:layout_width="wrap_content" 
Line 9: android:layout_height= "fill_parent"
Line 10: android:text="@string/entxt"
Line 11: android:hint="@string/entxt"      
       />


Line 12:  <TextView 
Line 13:  android:id="@+id/txxt"
Line 14:  android:layout_width="wrap_content" 
Line 15:  android:layout_height="wrap_content" 
Line 16: android:text="@string/t1"        
        />



    <Button 

Line 17: android:id="@+id/but"
Line 18: android:layout_width="wrap_content" 
Line 19: android:layout_height="wrap_content" 
Line 20: android:text="@string/but_lab"
Line 21: android:onClick="showtext"        
        />



</LinearLayout>

Line 1-5  I already explained in previous post
Line 7 To link the main.xml file and Java source through R.class file.There is crying need to create a id attribute "@+id/mytext. so that we can use in java source code.
Line 10 Here we using a string which shown when there is noting in Edit text box i.e default text or suggestive text we create a string either Graphical or edit in string.xml file. when you add string through the Graphical recourse it is automatically added in string.xml file


Line 10 Here we using a string which shown when there is noting in Edit text box i.e default text or suggestive text we create a string either Graphical or edit in string.xml file. when you add string through the Graphical recourse it is automatically added in string.xml file
   you can add string resource by typing string tag with name attribute  and the value of name attribute. It will automatically generated string resources in Graphical mode of string.xml
Line 11:android:hint="@string/entxt"   The hint attribute is used for suggestive text in Edit box
Line 13:android:id="@+id/txxt" it is another a id attribute for TextView
Line 16: android:text="@string/t1" t1 is string resources for android TextView
Line 17:android:id="@+id/but" Id attribute for button
Line 20:android:text="@string/but_lab" It is label name which show on the button.since again it is string resource it create same way as i told you. 
Line 21: android:onClick="showtext"   "showtext" is the name of function it call when onClick event occurred.since it link with the onClick event.   
      
When mention the name of function in main.xml file and do not define the function in Java source file.On execution of application as soon as click the button This above kind of screen is show.
  Explanation:- When you press the button ,you trying to update the  View  i.e. added a new String resources and modified the view. for the button a click event is define but it did not get any function which define the action so it gives error.

Line:1 public void showtext(View view)
{
Line:2        EditText ed = (EditText)findViewById(R.id.mytext);
Line:3        TextView tv = (TextView)findViewById(R.id.txxt);
Line:4        tv.setText(ed.getText());     
    }



Line 1: public void showtext(View view) It is the name of function it contains view object
Line 2,3:  EditText ed = (EditText)findViewById(R.id.mytext) I already told that findViewById(R.id.resource id) i.e similar method to JavaScript in which we use the getdooucmentById().findViewById  can reference the EditText but  you access through R.class it is View kind of object hence it is very necessary to cast to EditText and TextView as requirement.
Line 4:tv.setText(ed.getText())-getText and setText is method by which get value of EditText View and that value is set to TextView 
  Now you compile the application
 



Friday, 8 June 2012

Descripition of your First Android program

Now I explain one by one first of all we see the architecture of file formed 

There many important file and directories are created.
AndroidManifest.xml : It is configuration file which is formed for Helloandroid application

Default.properties or project.properties: It is used by Eclipse and android. Hence please do not edit this file.

/src folder: It contain source code of Helloandroid

/gen/hell.abh.com/HelloandroidActivity.java: The name of Application which is created i.e. named as "HelloandroidActivity"


/gen/hell.abh.com/R.java: It is generated Resource file  do not edit this file.

 /assets folder:Here uncomplied file resource stored.

/res folder: it is place where application resource include such as graphic,animation ,layout file and row file.

/res/drawable:Application icon graphic resource which is default stored.

/res/layout/main.xml: It is layout file used for Helloandroid project.It is very important file.

/res/values/string.xml: It is path where string resources are defined. Here string is resources for android. actually it is value folder it is very important folder it define resouces such as
 arrays.xml-Xml file define the array
colors.xml-Xml file define color.It define background color for UI
dimens.xml-Xml file which define value of UI eg 40px,40px by R.dimens class,
string.xml-Xml file used to define text String to be used in your application
styles.xml-Xml file which is define the style of application

 

 I am going to explain the main.xml which lie under /res/layout/main.xml   
    The layout of the application can be determine by the xml.file or source code . main.xml is a file which determine the layout your application i.e. user interface before explaining each line of main.xml I want to tell what is view ?


        View:  Views are user interface as object such as button or TextField, Radiobutton etc. and ViewGroup is container which determine how the views are laid out such as Grid or vertical. you would notice one important thing by seeing the above chart it is clear that ViewGroup may consist of ViewGruop and View also but View can never consist ViewGroup.
      When you make any new android application. Two view is always formed LinearLayout and TextView . 

Line 1:<?xml version="1.0" encoding="utf-8"?>
xml version="1.0" is simple version which is used currently specify in form of "1.x"
 encoding ="utf-8It may be possible that Xml file may contain the non ASCII characters, so we have to use unicode

Line 2:<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 <LinearLayout is Tag of LinearLayout which is default  defined in the android application LinearLayout Tag.The namespace is defined by the xmlns attribute in the start tag(LinearLayout) of an element.The namespace declaration has the following syntax. xmlns:prefix="URI". namespace(prefix android) is used in each line main.xml file.



Line 3: android:layout_width="fill_parent"
android is namespace and layout_width is the attribute of LinearLayout tag. fill_parent is value of attribute .fill_parents stretches the contents to fill container.you can choose the number of value by pressing CTRL+SPACEBAR 

Line 4: android:layout_height="fill_parent"
layout_height is attribute of LinearLayout tag. The value of layout_height is fill_parent and wrap_content.The wrap_content means Views occupies the place in container as it should be.

Line 5:android:orientation="vertical"
android:orientation define the layout orientation it may be specify the vertical or Horizontal


Line 6:<TextView
 <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

 TextView is simple a Text.android:layout_width="fill_parent" and android:layout_height="wrap_content" has a same explanation as i above is given

 android:text="@string/hello" />
There is two method for set the android:text
(1) The first Method  is the set the android:text attribute to raw string
<TextView
    -----------
   -----------
android:text="It is my first porgram" />

(2)The second method is the use the string resources called "my_program" which should be define in string.xml file
 
<TextView
    -----------
   -----------
android:text="@string/my_program" /> 

When you use first method android SDK give warning   "Hardcoded string "hello", should use @string resource" you may ignore. when you use second method you must edit explcity in string.xml file in resource file 
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="hello">It is my first android program</string>
    <string name="app_name">Helloandroid</string>

</resources>

but i prefer that you must use second method.


 It is Graphical representaion of string.xml. Here is two string resouce is given 
hello(String)
app_name(String)
you can change the value of both attribute.Here we change the value of Hello string "It is my first android program". you must save before going forward


When you change These change reflect in the  file (string.xml). resource file when you edit
 String resources through the Graphical mode, automatically string.xml resource file updated


Now execute the program once again.your change will reflect in program.

package hello.abh.com;

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

public class HelloandroidActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

Line 1: package hell.abh.com this is namespace conversion in every android application

Line 2:  import android.app.Activity Since each application is start with a activity Activity is necessary to imported


Line 3: import android.os.Bundle is another package which is needed.

Line 4: HelloandroidActivity is our class which extends Activity class.

Line 5:public void onCreate(Bundle savedInstanceState) it is method of Activity class which is overridden it has parameter savedInstanceState.It is current state information is bundled as savedInstanceState in other word we can say that All current state information is bundled as in savedInstanceState  that is object which held in memory.Here we will not directly handle but we must be aware of the presence 

Line 6:super.onCreate(savedInstanceState) This line is very important because it call to base Activity class to perform setup work for Helloandroid. If you do not write this line , you will receive run-time exception error. Remember it always call under onCreate(BudlesavedInstanceState)



Before explaining the line setContentView(R.layout.main) we want to tell what is R in this code
R is stand for Resources. we have been  talking about only two file main.xml and Helloandroid.java.source file.main.xml is a xml file which determine the layout of the application and Helloandroid is source code which used main.xml file with the help or R.class file.R.class file act as communication link between your source code and main.xml file.
It has all  reference ID of all the resources in your res/ directory .source code link the main.xml file through the reference IDs which is generated in R.Java file.

if you see carefully  R.java file four reference id ic_launcher,main,app_name,hell. When you complied your application There is  aapt tool that generate generates the R. class. 
I told you that R.java file create all Reference id for /res folder if you see carefully in the Right hand of panel you will see ic_launcher.png under /res/drawable-hdpi file that is default image which shown when you execute the program.There is main.xml under /res/layout/main.xml and /res/values/string.xml first one is main.xml resource and latter strings.xml resource

There are two ways you can access a resource:
  1. In source code: By using syntex:eg Syntex- R. resource type.resource name
    R.string.hello.actually since it is static class 
    string is the resource type and hello is the resource name.
  2. In XML file: By using  a special XML syntax that also use  resource ID defined in your R class, such as:
    @string/hello
    string is the resource type and hello is the resource name. You can use this syntax in an XML resource any place.  
setContentView(R.layout.main)- It is  method setContentView (R.layout.main) which  sets the Activity's contents to specific resources that is main.xml (layout directory) through pointer in (R,java).file. The main.xml file contains size of Helloandroid screen and TextView.
  
Android is based upon the MVC pattern but There is no programming which is universally perfectly framed  in MVC pattern. MVC is a concept rather than a programming framework . You can implement your own MVC in any platforms. As long as you stick to the following basic idea
  1. Model: What to render
  2. View: How to render
  3. Controller: Events, user interface input
All about the view concern of the android application we done by main.xml file and we placed externally all resources in /res folder.