Saturday, 28 July 2012

Android Grid View Tutorial


Introduction of Android Grid View



Android provides data display in form of grid. That purpose we use grid view.

How to define
  • make a string letters
     static final String[] letters = new String[] { 
    			"D", "U", "N"
    			"I", "Y", "A"};
     


    Above we formed string of letters.
  • Then get grid view object.

    gridView = (GridView) findViewById(R.id.gridView1);
  • set array adapter to grid

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
    				android.R.layout.simple_list_item_1, letters);
     
    gridView.setAdapter(adapter);
    
  • set listener to gridview
     
    gridView.setOnItemClickListener(new OnItemClickListener() {
       public void onItemClick(AdapterView<?> parent, View v,
    				int position, long id) {
    			  
    			  your code
    			  
    			  }
    		});
     
Example
  1. Make layout file(main.xml).

    <?xml version="1.0" encoding="utf-8"?>
    
    <GridView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/gridView1"
        android:numColumns="auto_fit"
        android:gravity="center"
        android:columnWidth="50dp"
        android:stretchMode="columnWidth"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
     
    <TextView/>
    
  2. Define list and add listener that show item
    public class GridViewActivity extends ListActivity {
     
    	GridView gridView;
     
    	static final String[] letters = new String[] { 
    			"D", "U", "N"
    			"I", "Y", "A"};
     
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
     
    		setContentView(R.layout.main);
     
    		gridView = (GridView) findViewById(R.id.gridView1);
     
    		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
    				android.R.layout.simple_list_item_1, letters);
     
    		gridView.setAdapter(adapter);
     
    		gridView.setOnItemClickListener(new OnItemClickListener() {
    			public void onItemClick(AdapterView<?> parent, View v,
    				int position, long id) {
    			   Toast.makeText(getApplicationContext(),
    				((TextView) v).getText(), Toast.LENGTH_SHORT).show();
    			}
    		});
     
    	}
     
    }
    
  3. Output : 


Android List View Tutorial


Introduction of Android List View


Android provides data display in form of list. That purpose we use list view.

How to define
  • make a string list
     static final String[] STATES = new String[] 
     { "Rajasthan", "Delhi", "Bombay","MP", "UP"};
     


    Above we formed list of indian states.
  • Then set list adapter with our string list.

    setListAdapter(new ArrayAdapter<String>(this, R.layout.main,STATES));
  • Then get list object
     ListView listView = getListView();
     
  • Using above listview set listener
     listView.setOnItemClickListener(new OnItemClickListener() {
     public void onItemClick(AdapterView<?> parent, View view,
    					int position, long id) {
    					
    					your code;
    					
    					}
     
     });
     
Example Above text view set list in text view.
  1. Make layout file(main.xml).

    <?xml version="1.0" encoding="utf-8"?>
    
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="10dp"
        android:textSize="10sp">
     
    <TextView/>
    
  2. Define list and add listener that show item
    public class ListStateActivity extends ListActivity {
     
    	static final String[] STATES = new String[] { "Rajasthan", "Delhi", "Bombay",
    			"MP", "UP"};
     
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
     
    		// no more this
    		// setContentView(R.layout.main);
     
    setListAdapter(new ArrayAdapter<String>(this, R.layout.main,STATES));
     
    ListView listView = getListView();
    listView.setTextFilterEnabled(true);
     
    listView.setOnItemClickListener(new OnItemClickListener() {
    			
    public void onItemClick(AdapterView<?> parent, View view,
    					
    int position, long id) {
    // When clicked, show a toast with the TextView text
    
    
    Toast.makeText(getApplicationContext(),
    ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
    			}
    		});
     
    	}
     
    }
    
  3. Output : 



Android Table Layout Tutorial


Introduction of Android Table Layout


Every android control is put in predefined layout. layout provides to arrange android controls. Table layout used to define control in table format. Android uses table row concept. In table row we can define our new control.

How to define table layout

Android use seperate file for layout. This file stored in android res/layout directory.

syntex :
 <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tableLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
 
 <TableRow
        android:id="@+id/tableRow1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5dip">   
  
    put your control
    
 </TableRow>
 
  <TableLayout/>

 
Above syntex define following properties
  • android:layout_width this property is used to define width.
  • android:layout_height this property is used to define height.
Example
  1. Make layout file(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">
     
     <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="5dip"> 
            
     <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button 1" />
     </TableRow>
             
     <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="5dip">      
              
     <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button 2" />
            
      </TableRow>
       
     </TableLayout>
    
  2. Output : 

   

Android Relative Layout Tutorial


Introduction of Android Relative Layout



Every android control is put in predefined layout. layout provides to arrange android controls. relative layout position android controls relative to another. Using this developer can display his desire UI. For defining relative position we use android:layout_below,layout_toRightOf,layout_toLeftOf etc. properties.

How to define Relative layout

Android use seperate file for layout. This file stored in android res/layout directory.

syntex :
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
 
  <RelativeLayout/>

 
Above syntex define following properties
  • android:layout_width this property is used to define width.
  • android:layout_height this property is used to define height.
Example
  1. Make layout file(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">
     
     <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button 1" />
     <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button 2" 
            android:layout_below="@+id/btnButton1"/>
     
     </RelativeLayout>
    
  2. Output : 


            

Sunday, 22 July 2012

Android Linear Layout Tutorial


Introduction of Android Linear Layout



Every android control is put in predefined layout. layout provides to arrange android controls. linear layout is mostly used to define application gui. In this we provide orientation of layout.

How to define linear layout

Android use seperate file for layout. This file stored in android res/layout directory.

syntex :
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
 
  <LinearLayout/>

 
Above syntex define following properties
  • android:layout_width this property is used to define width.
  • android:layout_height this property is used to define height.
  • android:orientation this property is used to define orientation of layout(horizontal or vertical)
Example
  1. Make layout file(main.xml) which contains two buttons in vertical.

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
     
     <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button 1" />
     <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button 2" />
     
     </LinearLayout>
    
  2. Output : 

           

Saturday, 21 July 2012

Android Checkbox Tutorial


Introduction of Android Checkbox Control



Android provides checkbox functionality. Using this control we can provide multiple choice to users.

How to define checkbox control

Android use seperate file for layout. This file stored in android res/layout directory.

syntex :
 <CheckBox
        android:id="@+id/chkandroid"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Android"/>

 
Above syntex define textbox with following properties
  • android:id a unique id provided.
  • android:layout_width this property is used to define width.
  • android:layout_height this property is used to define height.
set OnClickListener for checkbox. We need to set it manually.
How to set OnClickListener
  • First identify your checkbox.
     Syntex :
     
     chkandroid = (CheckBox) findViewById(R.id.chkandroid);
     
  • Then set event to this control
    chkandroid.setOnClickListener(new OnClickListener() {
     
       @Override
       public void onClick(View arg0) {
                    write your code
       }
     
      });
     
Example
  1. Make layout file(main.xml) which contains a checkbox. If we check on checkbox it display a message.

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
     
     <CheckBox
            android:id="@+id/chkandroid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Android"/>
            
     </LinearLayout>
    
  2. Then apply onclick event

    public class MyAndroidAppActivity extends Activity {
     
        private CheckBox chkandroid;
     @Override
     public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
            addListenerOnCheckbox();
     }
        public void addListenerOnCheckbox() {
     
     chkandroid = (CheckBox) findViewById(R.id.chkandroid);
     
     chkandroid.setOnClickListener(new OnClickListener() {
     
       @Override
       public void onClick(View v) {
                    //is chkIos checked?
      if (((CheckBox) v).isChecked()) 
      {
       Toast.makeText(this,"checked",Toast.LENGTH_LONG).show();
      }
      else
      {
          Toast.makeText(this,"Unchecked",Toast.LENGTH_LONG).show();
      }
     
       }
     });
     
      }
    }
    
    
  3. Output : 
                

Android Rating Bar Tutorial


Introduction of Android Rating Bar


Situation : We are using android application and we want to rate this.

For this purpose android provide rating bar control.
How to listen rating bar
  • First get the instance of rating bar.
     ratingBar = (RatingBar) findViewById(R.id.ratingBar);
     
  • Then apply the rating change listener for this rating bar.
     ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
      public void onRatingChanged(RatingBar ratingBar, float rating,boolean fromUser) {
      
       write your code
      
      }
     });
     
     
Example to display rating by user
  1. Make layout file(main.xml) which contains a button. If we click on button it change to screen2.

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
     
        <RatingBar
            android:id="@+id/ratingBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:numStars="4"
            android:stepSize="1.0"
            android:rating="2.0" />
     
    </LinearLayout>
    
  2. Then apply setOnRatingBarChangeListener

    public class mainactivity extends Activity {
     
     private RatingBar ratingBar;
     
     @Override
     public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      addListenerOnRatingBar();
     }
     
      public void addListenerOnRatingBar() {
     
     ratingBar = (RatingBar) findViewById(R.id.ratingBar);
     ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
      public void onRatingChanged(RatingBar ratingBar, float rating,boolean fromUser) {
     
          Toast.makeText(MyAndroidAppActivity.this,
           String.valueOf(rating), Toast.LENGTH_SHORT).show();
     
      }
     });
     
    }
    
    
  3. Output : 


            

Android Spinner Tutorial


Introduction of Android Spinner



Situation : We want to display a list of states. But want to save space.

For this purpose android spinner control. This control provides a drop down list.
How to code spinner in android
  • First get the instance of rating bar.
     spinner1 = (Spinner) findViewById(R.id.spinner1);
     
  • Then add items to this spinner.
     
      List<String> list = new ArrayList<String>();
     list.add("Delhi");
     list.add("Bombay");
     list.add("Rajasthan");
     ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
      android.R.layout.simple_spinner_item, list);
     dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
     spinner1.setAdapter(dataAdapter);
     
     
    Here we first make list and then add to spinner.
Example to display spinner
  1. Make layout file(main.xml) which contains a button. If we click on button it change to screen2.

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
     
        <Spinner
            android:id="@+id/spinner1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
     
    </LinearLayout>
    
  2. Then apply setOnRatingBarChangeListener

    public class mainactivity extends Activity {
     
     private Spinner spinner1;
     
     @Override
     public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      addItemsOnSpinner1();
     }
     
     public void addItemsOnSpinner1() {
     
     spinner1 = (Spinner) findViewById(R.id.spinner1);
     List<String> list = new ArrayList<String>();
     list.add("Delhi");
     list.add("Bombay");
     list.add("Rajasthan");
     ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
      android.R.layout.simple_spinner_item, list);
     dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
     spinner1.setAdapter(dataAdapter);
      }
    }
    
    
  3. Output : 

                       
                 

Android Rating Datepicker Tutorial


Introduction of Android Datepicker




Android provide datepicker control.
How to make datepicker
  • First get the instance of datepicker.
     dpResult = (DatePicker) findViewById(R.id.dpResult);
     
  • Then get the calendar instance
     final Calendar c = Calendar.getInstance();
     
  • Get current day,month and year
     year = c.get(Calendar.YEAR);
    month = c.get(Calendar.MONTH);
    day = c.get(Calendar.DAY_OF_MONTH);
     
  • Set day,month and year in result way
     
     dpResult.init(year, month, day, null);
     
     
Example
  1. Make layout file(main.xml).

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
     
        <DatePicker
            android:id="@+id/dpResult"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
     
    </LinearLayout>
    
  2. Then apply setOnRatingBarChangeListener

    public class mainactivity extends Activity {
     
     private DatePicker dpResult;
     
     @Override
     public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
         setCurrentDate();
     }
     
     public void setCurrentDate() {
            private int year;
         private int month;
         private int day;
      dpResult = (DatePicker) findViewById(R.id.dpResult);
     
      final Calendar c = Calendar.getInstance();
      year = c.get(Calendar.YEAR);
      month = c.get(Calendar.MONTH);
      day = c.get(Calendar.DAY_OF_MONTH);
       dpResult.init(year, month, day, null);
     }
     
    }
    
    
  3. Output : 

                  

Android Rating Timepicker Tutorial


Introduction of Android Timepicker





Android Radio Button Tutorial


Introduction of Android Radio Button Control




Android provide radio control. It uses radio group feature to bind radio button into single group. So that user can select a single radio button from one group.

How to define radio control

Android use seperate file for layout. This file stored in android res/layout directory.

syntex :
 <android:id="@+id/radioSex"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
 <RadioButton
            android:id="@+id/radioMale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Male" 
            android:checked="true"/>
 <RadioButton
            android:id="@+id/radioFemale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Female"/>
 <RadioGroup/>

 
Above syntex define following properties
  • android:id a unique id provided.
  • android:layout_width this property is used to define width.
  • android:layout_height this property is used to define height.
Example
  1. Make layout file(main.xml) which contains a checkbox. If we check on checkbox it display a message.

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
     
     <android:id="@+id/radioSex"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
     <RadioButton
                android:id="@+id/radioMale"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Male" 
                android:checked="true"/>
     <RadioButton
                android:id="@+id/radioFemale"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Female"/>
     <RadioGroup/>
     
     <Button
            android:id="@+id/btnDisplay"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="show result" />
            
     </LinearLayout>
    
  2. Then apply onclick event

    public class MyAndroidAppActivity extends Activity {
     
        private CheckBox chkandroid;
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.main);
            addListenerOnButton();
    	}
         public void addListenerOnButton() {
     
    	radioSexGroup = (RadioGroup) findViewById(R.id.radioSex);
    	btnDisplay = (Button) findViewById(R.id.btnDisplay);
     
    	btnDisplay.setOnClickListener(new OnClickListener() {
     
    		@Override
    		public void onClick(View v) {
     
    		        // get selected radio button from radioGroup
    			int selectedId = radioSexGroup.getCheckedRadioButtonId();
     
    			// find the radiobutton by returned id
    		        radioSexButton = (RadioButton) findViewById(selectedId);
     
    			Toast.makeText(MyAndroidAppActivity.this,
    				radioSexButton.getText(), Toast.LENGTH_SHORT).show();
     
    		}
     
    	});
     
      }
    }
    
    
  3. Output :

            

Android Textbox Tutorial


Introduction of Android Textbox Control



Android provides textbox Control for user interface. Textbox control user can enter information and submit. It is like webpage textbox that can be used multiple purposes.

How to define textbox control

Android use seperate file for layout. This file stored in android res/layout directory.

syntex :
 <TextView
        android:id="@+id/txtname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
 <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="show text" />        
 
Above syntex define textbox with following properties
  • android:id a unique id provided.
  • android:layout_width this property is used to define width.
  • android:layout_heightthis property is used to define height.
set OnClickListener for button. We need to set it manually.
How to set OnClickListener to button
  • First identify your button.
     Syntex :
     
     button = (Button) findViewById(R.id.button1);
     
  • Then set event to this button control
     button.setOnClickListener(new OnClickListener() {
     
    			@Override
    			public void onClick(View arg0) {
                    write your code
    			}
     
    		});
     
  • Then get textbox content and display it
     TextView txtname = (TextView) findViewById(R.id.txtname);
     String name=txtname.getText().toString()
     Toast.makeText(this,name,Toast.LENGTH_LONG).show();
     
Example
  1. Make layout file(main.xml) which contains a button. If we click on button it display a message.

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
     
     <TextView
            android:id="@+id/txtname"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
     <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="show text" />  
     
    </LinearLayout>
    
  2. Then apply onclick event

    public class MyAndroidAppActivity extends Activity {
     
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.main);
     
    		addListenerOnButton();
     
    	}
     
    	public void addListenerOnButton() {
     
    		Button button = (Button) findViewById(R.id.button1);
     
    		button.setOnClickListener(new OnClickListener() {
     
    			@Override
    			public void onClick(View arg0) {
     
                 TextView txtname = (TextView) findViewById(R.id.txtname);
                 String name=txtname.getText().toString()
                 Toast.makeText(this,name,Toast.LENGTH_LONG).show();
    			}
     
    		});
     
    	}
     
    }
    
    
  3. Output : 


     

Android Button Tutorial


Introduction of Android Button Control


Android provides Button Control for user interface. Button control provides click event to developers. Using this developer can perform additional task.

How to define button control

Android use seperate file for layout. This file stored in android res/layout directory.

syntex :
 <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click me" />
 
Above syntex define button with following properties
  • android:id a unique id provided to each button.
  • android:layout_width this property is used to define button width.
  • android:layout_heightthis property is used to define button height.
  • android:textThis property define text which is seen by users
Android provides OnClickListener for button. We need to set it manually.
How to set OnClickListener to button
  • First identify your button.
     Syntex :
     
     button = (Button) findViewById(R.id.button1);
     
  • Then set event to this button control
     button.setOnClickListener(new OnClickListener() {
     
    			@Override
    			public void onClick(View arg0) {
                    write your code
    			}
     
    		});
     
Example
  1. Make layout file(main.xml) which contains a button. If we click on button it display a message.

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
     
    <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Show Toast" />
     
    </LinearLayout>
    
  2. Then apply onclick event

    public class MyAndroidAppActivity extends Activity {
     
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.main);
     
    		addListenerOnButton();
     
    	}
     
    	public void addListenerOnButton() {
     
    		Button button = (Button) findViewById(R.id.button1);
     
    		button.setOnClickListener(new OnClickListener() {
     
    			@Override
    			public void onClick(View arg0) {
     
                     Toast.makeText(this, 
                                   "Button is clicked", Toast.LENGTH_LONG).show();
    			}
     
    		});
     
    	}
     
    }
    
    
  3. Output : 

             

Android ProgressBar Tutorial


Introduction of Android ProgressBar Control



Situation : If someone drove bike. Bike has speedometer. This show bike speed. as we accelerate bike speedometer also show relative speed.

Conclusion : Speedometer shows progress of bike speed. Same thing or concept we apply with android progressbar. This progress bar shows our task progress.

Progress bar always used for long time running task in android. So that user aware about this.
How to use progress bar
  1. Make object of progressbar.
     ProgressDialog progressBar=new ProgressDialog(this);
     
  2. Then set properties for this progressbar
                progressBar.setCancelable(true);
    			progressBar.setMessage("File downloading ...");
    			progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    			progressBar.setProgress(0);
    			progressBar.setMax(100);
    			progressBar.show();
     
  3. Start Background thread that perform long running task.
     new Thread(new Runnable() {
    			  public void run() {
    			  
    			  }
    			}).start();
     
  4. Update progress bar status using progressBarHandler object. This object is created in following way.
      Handler progressBarHandler = new Handler();
      progressBarHandler.post(new Runnable() {
    					public void run() {
    					  progressBar.setProgress(progressBarStatus);
    					}
    				  });
     

    Here progressBarStatus is integer variable which is updated as your task.
  5. If long running task completed then dismiss progressbar
     progressBar.dismiss();
    


    Example
    1. Make layout file which contains a button. If we click on button it show notification toast message.

      <?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" >
      
         
      
      
          <Button
      
              android:id="@+id/btnProgress"
      
              android:layout_width="wrap_content"
      
              android:layout_height="wrap_content"
      
              android:text="Download" />
      
      </LinearLayout>
      
      
    2. Then apply onclick event in mainactivity.class

      public class MyAndroidAppActivity extends Activity {
       
      	Button btnStartProgress;
      	ProgressDialog progressBar;
      	private int progressBarStatus = 0;
      	private Handler progressBarHandler = new Handler();
       
      	private long fileSize = 0;
       
      	@Override
      	public void onCreate(Bundle savedInstanceState) {
      		super.onCreate(savedInstanceState);
      		setContentView(R.layout.main);
       
      		addListenerOnButton();
       
      	}
       
      	public void addListenerOnButton() {
       
      	btnStartProgress = (Button) findViewById(R.id.btnProgress);
      		btnStartProgress.setOnClickListener(
                       new OnClickListener() {
       
      		   @Override
      		   public void onClick(View v) {
       
      			// prepare for a progress bar dialog
      			progressBar = new ProgressDialog(v.getContext());
      			progressBar.setCancelable(true);
      			progressBar.setMessage("File downloading ...");
      			progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
      			progressBar.setProgress(0);
      			progressBar.setMax(100);
      			progressBar.show();
       
      			//reset progress bar status
      			progressBarStatus = 0;
       
      			//reset filesize
      			fileSize = 0;
       
      			new Thread(new Runnable() {
      			  public void run() {
      				while (progressBarStatus < 100) {
       
      				  // process some tasks
      				  progressBarStatus =Tasksfunction();
       
      				  // your computer is too fast, sleep 1 second
      				  try {
      					Thread.sleep(1000);
      				  } catch (InterruptedException e) {
      					e.printStackTrace();
      				  }
       
      				  // Update the progress bar
      				  progressBarHandler.post(new Runnable() {
      					public void run() {
      					  progressBar.setProgress(progressBarStatus);
      					}
      				  });
      				}
       
      				// ok, file is downloaded,
      				if (progressBarStatus >= 100) {
       
      					// sleep 2 seconds, so that you can see the 100%
      					try {
      						Thread.sleep(2000);
      					} catch (InterruptedException e) {
      						e.printStackTrace();
      					}
       
      					// close the progress bar dialog
      					progressBar.dismiss();
      				}
      			  }
      		       }).start();
       
      	           }
       
                      });
       
              }
       
      	// file download simulator... a really simple
      	public int Tasksfunction() {
       
      		while (fileSize <= 1000000) {
       
      			fileSize++;
       
      			if (fileSize == 100000) {
      				return 10;
      			} else if (fileSize == 200000) {
      				return 20;
      			} else if (fileSize == 300000) {
      				return 30;
      			}
      			// ...add your own
       
      		}
       
      		return 100;
       
      	}
       
      }
      
      
    3. Output : 


                       

Android Alert Dialog Box Tutorial


Introduction of Alert Dialog Box Control



Situation : Everyone uses javascript confirm() function. This function display a message with user choice to yes or no. Same functionality in android achieved by alert dialog.
Android provides confirm functionality using alert dialog box. For using this feature we need to createAlertDialog.Builder object. In this we pass Current context.
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
Using this object we set following properties of this dialog.
  1. setTitle() : This function is used to set title of alert dialog box.

    Syntex :
    
    alertDialogBuilder.setTitle("Your Title");
    
  2. setCancelable () : This functionis used for cancellation of alert dialog box. We can set true or falsevalues.

    Syntex :
    
    alertDialogBuilder.setCancelable(false);
    
  3. setPositiveButton() : This function create a button with desired text. In our syntex("Yes"). If user click this button alert event which is attached to it triggered.

    Syntex :
    
    alertDialogBuilder.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
    					
    public void onClick(DialogInterface dialog,int id) {
                //  Task to perform
                
                
    					}
    				});
    
    
  4. setNegativeButton() : This function create a button with desired text. In our syntex("No"). If user click this button alert event which is attached to it triggered or cancel the alert dialog box.

    Syntex :
    
    alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
    					
    public void onClick(DialogInterface dialog,int id) {
    						
    // if this button is clicked, just close
    						
    // the dialog box and do nothing
    						
    dialog.cancel();
    					}
    				});
    
After setting above properties we use create() method to create alert dialog.
Syntex :

AlertDialog alertDialog = alertDialogBuilder.create();
At last step we show this alert dialog box. using show() method.
Syntex :

alertDialog.show();




Example
  1. Make layout file which contains a button. If we click on button it show alert dialog.

    <?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" >
    
       
    
    
        <Button
    
            android:id="@+id/buttonToast"
    
            android:layout_width="wrap_content"
    
            android:layout_height="wrap_content"
    
            android:text="Show Alert Box" />
    
    </LinearLayout>
    
  2. Then apply onclick event in mainactivity.class

    public class MainActivity extends Activity {
     
    	final Context context = this;
    	private Button button;
     
    	public void onCreate(Bundle savedInstanceState) {
     
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.main);
     
    		button = (Button) findViewById(R.id.buttonAlert);
     
    		// add button listener
    		button.setOnClickListener(new OnClickListener() {
     
    		@Override
    		public void onClick(View arg0) {
     
    			
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
    				context);
     
    			
    // set title
    
      alertDialogBuilder.setTitle("Your Title");
     
    			
    // set dialog message
    			
       alertDialogBuilder.setMessage("Click yes to exit!")
    		     .setCancelable(false)
    		     
    .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
    					
    public void onClick(DialogInterface dialog,int id) {
    						
    // if this button is clicked, close
    						
    // current activity
    						
    MainActivity.this.finish();
    					}
    				  })
    				
    .setNegativeButton("No",new DialogInterface.OnClickListener() {
    					
    public void onClick(DialogInterface dialog,int id) {
    						
    // if this button is clicked, just close
    						
    // the dialog box and do nothing
    						
    dialog.cancel();
    					}
    				});
      
    				// create alert dialog
    				
    AlertDialog alertDialog = alertDialogBuilder.create();
     
    				
    // show it
    				
    alertDialog.show();
    			}
    		});
    	}
    }
    
    
  3. Output : 
                 

Android Toast Tutorial


Introduction of Android Toast Control



Situation : Everyone uses javascript alert() function. This function display a message to user. Same functionality in android achieved by Toast.
Android use toast control for messaging(notification) purpose. Using this we can show any message to user. Android provides a limited time period for toast after that it becomes invisible.

Android provides Toast class. This class has makeText() method. this method set message which we want to display. After this we use show() method to display a message to users.
 Syntex :
 
 
 Toast.makeText(ApplicationContext,message,Time to display).show();
 
 
makeText() method 

This method needs following parameters
  1. First we need to set current ApplicationContext. We can get current application context usingthis.getApplicationContext property.
  2. Then as second parameter we need to set message. User can set desired message.
  3. Then we need to set time period to display. For this purpose android provides inbuilt timer.
    • Toast.LENGTH_LONG : this set message for long time duration.
    • Toast.LENGTH_SHORT : this set message for short time duration.
show() method

this method is helpful for showing message to user.
Example
  1. Make layout file which contains a button. If we click on button it show notification toast message.

    <?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" >
    
       
    
    
        <Button
    
            android:id="@+id/buttonToast"
    
            android:layout_width="wrap_content"
    
            android:layout_height="wrap_content"
    
            android:text="Toast Message" />
    
    </LinearLayout>
    
  2. Then apply onclick event in mainactivity.class

    public class MainActivity extends Activity {
     
    	private Button button;
     
    	public void onCreate(Bundle savedInstanceState) {
     
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.main);
     
    		button = (Button) findViewById(R.id.buttonToast);
     
    		button.setOnClickListener(new OnClickListener() {
     
    			  @Override
    			  public void onClick(View arg0) {
     
    			     Toast.makeText(getApplicationContext(), 
                                   "Button is clicked", Toast.LENGTH_LONG).show();
     
    			  }
    		});
    	}
    }
    
    
  3. Output : 
                    
      

Android Intent Tutorial

Introduction of Android Intent


Situation : A company wants to recruit employee for any project. so it use it's advertisement service. Any person who is suitable can apply for this job and complete company project.

Conclusion : Here advertisement service works as intent. which is a interface between company and employee. means intent is a way to pass information in android plateform. As company can recruit employee as it's requirement and then publish advertisement. So intent is run time entity.

We can say intent as asynchronous message (information) passing in android system. This message is passed among android activity, services, broadcast receiver etc.

syntex :
 Intent intent = new Intent(context,NameOfJavaClassToCall.class);
 startActivity(intent);
From above we need to create standard intent object which contain current context and name of java class to be called. Then we need to use startActivity() method to call new activity. In this method we pass out intent object.

How to pass message(information)

For passing information between two android activity we use android putExtra() method which contains a key-value concept.

Syntex :
Intent intent = new Intent(context,NameOfJavaClassToCall.class);
intent.putExtra("key","value");
startActivity(intent);
How to receive intent into another class 

For receiving information into another class we use android getIntent().getExtras() method. This method return message in form of bundle. So we need to create bundle object to get intent. Then we usegetString() method with desired key to get data.
Syntex :

Bundle extras = getIntent().getExtras();
String value = extras.getString(key);


Example
  1. Make layout file(main.xml) which contains a button. If we click on button it change to screen2.

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
     
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="screen 1 (main.xml)"/>
     
        <Button
            android:id="@+id/button1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Click me to another screen" />
     
    </LinearLayout>
    
  2. Make layout file(main2.xml) which contains a button. If we click on button it change to screen1.

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
     
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="screen 1 (main.xml)"/>
     
        <Button
            android:id="@+id/button1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Click me to another screen" />
     
    </LinearLayout>
    
  3. Then apply onclick event in mainactivity.class to switch screen 1 to screen 2

    public class mainactivity extends Activity {
     
    	Button button;
     
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.main);
    		addListenerOnButton();
    	}
     
    	public void addListenerOnButton() {
     
    		final Context context = this;
     
    		button = (Button) findViewById(R.id.button1);
     
    		button.setOnClickListener(new OnClickListener() {
     
    			@Override
    			public void onClick(View arg0) {
     
    			    Intent intent = new Intent(context, mainactivity2.class);
                                startActivity(intent);   
     
    			}
     
    		});
     
    	}
     
    }
    
    
  4. Then apply onclick event in mainactivity2.class to switch from screen 2 to screen 1

    public class mainactivity2 extends Activity {
     
    	Button button;
     
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.main2);
    		addListenerOnButton();
    	}
     
    	public void addListenerOnButton() {
     
    		final Context context = this;
     
    		button = (Button) findViewById(R.id.button1);
     
    		button.setOnClickListener(new OnClickListener() {
     
    			@Override
    			public void onClick(View arg0) {
     
    			    Intent intent = new Intent(context, mainactivity.class);
                                startActivity(intent);   
     
    			}
     
    		});
     
    	}
     
    }
    
    
  5. Output : 






Introduction of Android Manifeast File


Introduction of Android Manifeast File


Android manifest file control whole application. This file defines all primary task related to activity, services, permission to access android resources, android sdk version for application.

Example of Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.programmingduniya"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Language"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <uses-sdk android:minSdkVersion="10" />
    <uses-permission android:name="ACCESS_NETWORK_STATE">      
</manifest> 
Manifest tag in android manifest file define following attribute.
  1. package : android package attribute define java file directory or library. This attribute always unique for each application. For this purpose android use domain reverse name methodology. This way avoid conflict with other android apps library.
  2. versionCode : android version code define sequence of our app. This is Integer value and must start with 1 for first time. This attribute helps android system to detect any update in application.
  3. VersionName : android version name useful for users. This is String value. This is display to user to read version name of application.
Android use application tag to start our application. This tag has following sub tag.
  1. activity : This define android java class name. for this purpose we use android:name attribute. In this attribute we define our activity with dot.
  2. intent-filter : This tag is used for main activity of application. this define two sub tags
    • action : It is used for main activity. for this purposse we need to use "android.intent.action.MAIN" value.
    • category : This is used to add main activity to android application directory. for this purpose we need to use "android.intent.category.LAUNCHER" value.
  3. service : for starting service we use this tag.
uses-sdk tag in android manifest file define minimum android device version where application runs.
uses-permission tag in android manifest define permission for accessing various android resource.

Introduction of Android Application Architecture


Introduction of Android Application Architecture

Android application is composed of following files
  • Java classes
  • Android manifest
  • Resources
  • Files
Java classes : Android provides several base classes to develope android application. Class hierarchy diagram is

View : View class in android is used at design time of android application. This class provides all necessary object(button,image,text etc.) for android application. View class is used in android xml file where tree structure provided by android.

Activity : activity class and its subclasses are the ones that provide logic behind the GUI. Actually it corresponds to ViewModel in Model-View-ViewModel architecture pattern (MVVM). Relationship between subclasses of Activity and GUI layout is 1-to-1; normally each subclass of Activity has one GUI layout associated with it and vice-versa. Activity has a lifecycle.

ContentProvider : ContentProvider class and its subclasses correspond to Model in MVVM architecture. In most practical cases it is a wrapper around SQLite database with rather fancy URI-based way to query the database. Theoretically nobody prevents a developer from building ContentProvider which will be using something else instead of DB for storing data. However given that query() method of ContentProvider returns Cursor object which is quite similar to JDBC ResultSet interface and the way how the query is made, nobody would doubt that the real purpose of ContentProviders is to encapsulate a database.


Think of this: Activity is active and running only when its GUI is on foreground. As soon as another Activity GUI comes in front of the current one, the current one stops running even if it was doing something. And what if you need to perform certain operation even when the process which tries to perform it is not on foreground? You can’t do this with Activity. You can’t do this with ContentProvider as well since it does not have its own lifecycle and it can run only while Activity which uses it is active.


Service : Service has a lifecycle. This means that it can be instantiated and run by Android application framework under certain conditions It can be executed even when the process it runs within is not on a foreground. So if you develop Activity which must perform a long running operation which should be completed even while running in background, you should create Service implementing that operation and invoke it from Activity.
BroadcastReceiver : BroadcastReceiver class and its subclasses serve as “subscribers” in communication mechanism implemented by Android application architecture.
Intent : Intent class and its subclasses serve as messages in message passing in communication mechanisms implemented by Android application architecture.
Android manifest : Android manifest is an XML file and it serves several functions. Here is Google description of manifest functions.
  • It names the Java package for the application. The package name serves as a unique identifier for the application.
  • It describes the components of the application — the activities, services, broadcast receivers, and content providers that the application is composed of.
  • It declares which permissions the application must have in order to access protected parts of the API and interact with other applications.
  • It declares the minimum level of the Android API that the application requires.
Resources : Any modern GUI application technology uses resources in some form. Android applications are not an exception of the rule. They use following types of resources:
  • Pictures
  • GUI layouts (XML files)
  • Menu definitions (XML files)
  • Textual strings
The way resources are referenced by Android applications is somewhat unusual. Normally in Java resources are identified by strings. Such strings may contain e.g. a path and a name of a file containing the picture or an ID of particular string etc. The problem with such approach is that mistakes in those references could not be caught during code translation.
Let’s consider following example. A file named mybutton.png contains a picture for a button. A developer makes a mistake and types mybuton.png as a reference to the resource in the code instead of using the correct file name. As a result the code is instructed to use nonexistent resource, but the code will compile just fine. The mistake may be discovered only during testing (and may not be discovered at all).
Google folks came with an elegant solution to the problem. Android application build generates a special Java class named R (just a single letter name) for each package where classes use resources. This class has a number of static final data members. Each such data member is a reference to a particular resource and they are used in Android Java code for referencing resources. Due to this each mistake in referencing resources is discovered at compile time.
Files : Android applications use several different types of files.
  • “General purpose” files
  • Database files
  • Opaque Binary Blob (OBB) files (those represent encrypted file systems on its own that can be mounted for the application)
  • Cached files

Android Platform


Android Platform


Android software layers : Android has seperate layer for different task. This method of layer seperation divide android processing into different groups. Each layer is responsible for their respective task.
  • Base layer : this layer is used for linux processing which manage all android device task related to device power, file etc.
  • Library management : this layer is used for android media, database etc. management.
  • Android Runtime management : this is used for dalvik virtual machine.
  • Application framework management : this is used for content provider, notification etc.
  • Front end management : this is used for front end management.



Android SDK comes with follwing supported libraries.
  • android.jar : this contains android supported library
  • documention.html and docs directory : this is provided for android developer help so they can easily understand android and it's library.
  • Samples directory : this directory contains simple program for android developers.
  • Tools directory : this directory is used by developer for command line access to android.

Introduction of Android


Today Android apps has a seperate market. This is provided by google and based on linux and java programming. This tool is used for mobile applications and famous in form of Android SDK (Software Developement Toolkit). Android SDK provides all basic utilities for developing, debugging, Testing android applications with android emulator. All android applications are distributed using google play service.

http://play.google.com

This service of google provide single way to distribute android application to android users in form of paid or free.

Android development is done by Eclipse IDE for java and use Dalvik Virtual Machine to run Java based applications. Dalvik uses an own bytecode format which is different from Java bytecode.
What is Android .apk
Android applications are primarily written in the Java programming language. The Java source files are converted to Java class files by the Java compiler.

The Android SDK contains a tool called dx which converts Java class files into a .dex (Dalvik Executable) file. All class files of one application are placed in one compressed .dex file. During this conversion process redundant information in the class files are optimized in the .dex file. For example if the same String is found in different class files, the .dex file contains only once reference of this String.

These dex files are therefore much smaller in size than the corresponding class files.

The .dex file and the resources of an Android project, e.g. the images and XML files, are packed into an .apk (Android Package) file. The program aapt (Android Asset Packaging Tool) performs this packaging.

The resulting .apk file contains all necessary data to run the Android application and can be deployed to an Android device via the adb tool.