Thursday, June 13, 2013

Interface in java


 An interface is a group or collection of abstract methods or incomplete methods. A class implements methods should override declared method in interface. All methods should be public in interface because of access of method in implemented class.
 An interface is implicitly abstract so we don't need to use abstract keyword. And all method of interface also by default abstract and incomplete.

Points for interface declaration and use:

1:- Method of interface should not static and final, You can't create static methods in interfaces. All methods are instance methods.
2:- All variables in interface are by default public static final. So we don't need to use it. if we use it , it will be redundant.
3:- Interface can not be instantiated.
4:- Interface have .java extension.


Example:-

public abstract interface TestInterface{   // Interfaces are always abstract

public static final String EX_CONSTANT = "ABC";
public static final int EX_INT_CONSTANT = 5;
public static final double EX_DOUBLE = 5.0;
public static final Integer EX_INTEGER = 10;

public void testMethod(); // Interface methods are always public
    abstract void anotherTestMethod(); // Also redundant

}

Difference between Interface and Class :-

1:- we can not create object of interface.
2:- it don't have constructor.
3:- Method of interface are abstract.
4:- It have incomplete methods.
5:- Method must be public.
6:- All variable is by default public static final.
7:- An interface can extends mulple interface.
8:- An interface not extended by class , it is implemented.

Example:-

/* File name : Dog.java */
interface Dog {

   public void bark();
   public void eat();
}


Now implementing interface in Behaviour.class

/* File name : Behaviour.java */
public class Behaviour implements Dog{

   public void eat(){
      System.out.println("eat");
   }

   public void bark(){
      System.out.println("bark");
   }

 

   public static void main(String args[]){
      Behaviour obj = new Behaviour();
      obj.eat();
      obj.bark();
   }
}

Saturday, June 1, 2013

Abstracttion with Abstract class

Abstraction is the ability to provide a class abstract in OOP. Abstract class can not be instantiated. All other property of Abstract class is same as normal class. but we can not instantiate abstract class.

We have to use abstract keyword to declare abstract class.



/* File name : Company.java */
public abstract class Company
{
   private String a;
   private String b;
   private int c;
   public Company(String a, String b, int c)
   {
      System.out.println("constructor");
      this.a= a;
      this.b= b;
      this.c= c;
   }
   public double a()
   {
     System.out.println("a");
     return 0.0;
   }
   public void b()
   {
      System.out.println("b");
   }
   public String toString()
   {
      return a+ " " + b+ " " + c;
   }

   public String b()
   {
      return b;
   }

}


Above class have same declaration and implementation just like simple class. but is have declared as abstract class. But the question is What is the difference between Abstract class and normal class.
I have provide below example to understand abstract class.


if you would try as follows:

/* File name : AbstractDemo.java */
public class AbstractDemo
{
   public static void main(String [] args)
   {
 
      Company e = new Company("Abhi", "India", 22);

      System.out.println("\n its my name--");
      e.b();
    }
}


 When we compile above class then you would get following error:

Company .java:46: Employee is abstract; cannot be instantiated

      Company e = new Company ("abhi.", "india", 22);
                   ^
1 error

We can not instantiate Abstract Class. rather you can create instance of  anonymous subclass of your abstract class. below example describes how can i do it.


public class AbstractDemo
{
   public static void main(String [] args)
   {
   
      Company e = new Company("Abhi", "India"){

      @Override
        public void mailCheck() {  // You need to implement abstract method
            System.out.print("Abstract");
        }

                               };

      e.b();
    }
}


From above example we can instantiate abstract class anonymous subclass.

Thursday, May 30, 2013

Lambda Expression in Java 8

Current New topic in Java 8 is lambda expressions.Lambda expressions are just like  methods, a body and return type and it has arguments. It is just like anonymous methods or we can say that method without name.

There are fallowing statement about Lembda Expressions:--

1) Lambda expression does't necessory to have parameters.
2) If there are no parameters to be passed, then an empty parentheses is given.
3) Type of the passed parameter can be explicitly declared or can be taken from context.
4) Lambda expression body does't necessory to have statements.
5) Body of expression should be enclosed in curly braces, if there is only one statement curly brace is not needed.
6) Lambda expression is converted into an instance of a functional interface.


There is fallowing example for lemda expression:----

 If we have fallowing list that we want to sort it. We can do it by fallowing way.

List<Person> personList = new ArrayList<>();
personList.add(new Person("Virat", "Kohli"));
personList.add(new Person("Arun", "Kumar"));
personList.add(new Person("Rajesh", "Mohan"));
personList.add(new Person("Rahul", "Dravid"));


//Sorting using Anonymous Inner class.
Collections.sort(personList, new Comparator<Person>(){
public int compare(Person p1, Person p2){
return p1.firstName.compareTo(p2.firstName);
}
});


But We Can reduce the code and more precise by using Lembda Expression as Fallowing:

Collections.sort(personList, (p1, p2) -> p1.firstName.compareTo(p2.firstName));
 



Pyramid Programs in C Languages:


Program 1:-

                              *
                            ***
                          *****
                        *******
                      *********


Solution:

#include <stdio.h>

int main()
{
   int row, c, n, temp;

   printf("Enter the number of rows in pyramid of stars you wish to see ");
   scanf("%d",&n);

   temp = n;

   for ( row = 1 ; row <= n ; row++ )
   {
      for ( c = 1 ; c < temp ; c++ )
         printf(" ");

      temp--;

      for ( c = 1 ; c <= 2*row - 1 ; c++ )
         printf("*");

      printf("\n");
   }

   return 0;
}



Output:-



-------------------------------------------------------------------------------------------------------------



Program 2:-


*
**
***
****
*****


Solution:--

#include <stdio.h>

int main()
{
    int n, c, k;

    printf("Enter number of rows\n");
    scanf("%d",&n);

    for ( c = 1 ; c <= n ; c++ )
    {
        for( k = 1 ; k <= c ; k++ )
            printf("*");

        printf("\n");
    }

    return 0;
}




------------------------------------------------------------------------------------------------------------





 A
B B
C C C
D D D D
E E E E E


Solution :--



#include<stdio.h>
int main()
{
    int i,j;
    char input,temp='A';
    printf("Enter uppercase character you want in triangle at last row: ");
    scanf("%c",&input);
    for(i=1;i<=(input-'A'+1);++i)
    {
        for(j=1;j<=i;++j)
           printf("%c",temp);
        ++temp;
        printf("\n");
    }
    return 0;
}

--------------------------------------------------------------------------------------------------------------



   *
      * * *
    * * * * *
  * * * * * * *
* * * * * * * * *



#include <stdio.h>
int main()
{
    int i,space,rows,k=0;
    printf("Enter the number of rows: ");
    scanf("%d",&rows);
    for(i=1;i<=rows;++i)
    {
        for(space=1;space<=rows-i;++space)
        {
           printf("  ");
        }
        while(k!=2*i-1)
        {
           printf("* ");
           ++k;
        }
        k=0;
        printf("\n");
    }
    return 0;
}




----------------------------------------------------------------------------------------------------------------



      1
      2 3 2
    3 4 5 4 3
  4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5



#include <stdio.h>
int main()
{
   int i,space,rows,k=0,count=0,count1=0;
   printf("Enter the number of rows: ");
   scanf("%d",&rows);
   for(i=1;i<=rows;++i)  
   {
       for(space=1;space<=rows-i;++space)
       {
          printf("  ");
          ++count;
        }
        while(k!=2*i-1)
        {
           if (count<=rows-1)
           {
             printf("%d ",(i+k));
             ++count;
           }
           else
           {
             ++count1;
              printf("%d ", (i+k-2*count1));
           }
           ++k;
        }
        count1=count=k=0;
        printf("\n");
    }
    return 0;
}



================================================================================


* * * * * * * * *
  * * * * * * *
    * * * * *
      * * *
        *
       
       
       
       
       
        #include<stdio.h>
int main()
{
    int rows,i,j,space;
    printf("Enter number of rows: ");
    scanf("%d",&rows);
    for(i=rows;i>=1;--i)
    {
        for(space=0;space<rows-i;++space)
           printf("  ");
        for(j=i;j<=2*i-1;++j)
          printf("* ");
        for(j=0;j<i-1;++j)
            printf("* ");
        printf("\n");
    }
    return 0;
}





=========================================================================



           1
         1   1
       1   2   1
     1   3   3    1
   1  4    6   4   1
 1  5   10   10  5   1

#include<stdio.h>
int main()
{
    int rows,coef=1,space,i,j;
    printf("Enter number of rows: ");
    scanf("%d",&rows);
    for(i=0;i<rows;i++)
    {
        for(space=1;space<=rows-i;space++)
        printf("  ");
        for(j=0;j<=i;j++)
        {
            if (j==0||i==0)
                coef=1;
            else
               coef=coef*(i-j+1)/j;
            printf("%4d",coef);
        }
        printf("\n");
    }
}



===========================================================================


1
2 3
4 5 6
7 8 9 10

#include<stdio.h>
int main()
{
    int rows,i,j,k=0;
    printf("Enter number of rows: ");
    scanf("%d",&rows);
    for(i=1;i<=rows;i++)
    {
        for(j=1;j<=i;++j)
          printf("%d ",k+j);
        ++k;
        printf("\n");
    }
}



Tuesday, May 28, 2013

Side Slider in for Android

Slider on side is more toughest task , i have try to implement it. Below code shows how to implement it.















1:- MainActivity.java:-


package com.example.sideslider;

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

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
CheckBox c1,c2,c3;
int key=0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final CustomisedPanel popup = (CustomisedPanel)
findViewById(R.id.popup_window);
popup.setVisibility(View.GONE);
final Button btn=(Button)findViewById(R.id.show_popup_button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if(key==0){
key=1;
popup.setVisibility(View.VISIBLE);
btn.setBackgroundResource(R.drawable.direction_right);
} else if(key==1){
key=0;
popup.setVisibility(View.GONE);
btn.setBackgroundResource(R.drawable.direction_right);
}
}
});
}
}

--------------------------------------------------------------------------------------------------------


2:-CustomisedPanel.java:-


 package com.example.sideslider;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.RectF;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.LinearLayout;
public class CustomisedPanel extends LinearLayout
{
private Paint innerPaint, borderPaint ;
public CustomisedPanel(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomisedPanel(Context context) {
super(context);
init();
}
private void init() {
innerPaint = new Paint();
innerPaint.setARGB(225, 75, 75, 75); //gray
innerPaint.setAntiAlias(true);
borderPaint = new Paint();
borderPaint.setARGB(255, 255, 255, 255);
borderPaint.setAntiAlias(true);
borderPaint.setStyle(Style.STROKE);
borderPaint.setStrokeWidth(2);
}
public void setInnerPaint(Paint innerPaint) {
this.innerPaint = innerPaint;
}
public void setBorderPaint(Paint borderPaint) {
this.borderPaint = borderPaint;
}
@Override
protected void dispatchDraw(Canvas canvas) {
RectF drawRect = new RectF();
drawRect.set(0,0, getMeasuredWidth(), getMeasuredHeight());
canvas.drawRoundRect(drawRect, 5, 5, innerPaint);
canvas.drawRoundRect(drawRect, 5, 5, borderPaint);
super.dispatchDraw(canvas);
}
}
-----------------------------------------------------------------------------------------------



3:-main.xml


 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:gravity="center_vertical"
android:background="@drawable/rectangle"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.example.sideslider.CustomisedPanel
android:id="@+id/popup_window"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:padding="1px"
android:background="#ffffff">
<CheckBox android:id="@+id/check1"
android:layout_width="wrap_content"
android:textColor="#FFFFFF"
android:layout_height="wrap_content"
android:text="Satellite View" />
<CheckBox android:id="@+id/check2"
android:layout_width="wrap_content"
android:textColor="#FFFFFF"
android:layout_height="wrap_content"
android:text="Street View" />
<CheckBox android:id="@+id/check3"
android:textColor="#FFFFFF"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Traffic" />
</com.example.sideslider.CustomisedPanel>
<Button android:id="@+id/show_popup_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/direction_right"/>


</LinearLayout>
------------------------------------------------------------------------------------------------------





Android ListView Indexer



Below I have Declared all code , java classes, xml and Manifiest file also:- 



1:- SideIndex.java file

package andriod.abhi.sideindex;

import java.util.ArrayList;
import java.util.Arrays;

import de.helloandroid.sideindex.R;

import android.app.Activity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

public class SideIndex extends Activity
{
private GestureDetector mGestureDetector;

// x and y coordinates within our side index
private static float sideIndexX;
private static float sideIndexY;

// height of side index
private int sideIndexHeight;

// number of items in the side index
private int indexListSize;

// list with items for side index
private ArrayList<Object[]> indexList = null;

// an array with countries to display in the list
static String[] COUNTRY= new String[]

"British Virgin Islands", "Brunei", "Bulgaria", "Burkina Faso",
"Burundi", "Cote d'Ivoire", "Cambodia", "Cameroon", "Canada",
"Cape Verde", "Cayman Islands", "Central African Republic", "Chad",
"Chile", "China", "Reunion", "Romania", "Russia", "Rwanda",
"Sqo Tome and Principe", "Saint Helena", "Saint Kitts and Nevis",
"Saint Lucia", "Saint Pierre and Miquelon", "Belize", "Benin",
"Bermuda", "Bhutan", "Bolivia", "Christmas Island",
"Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo",
"Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus",
"Czech Republic", "Democratic Republic of the Congo", "Denmark",
"Djibouti", "Dominica", "Dominican Republic",
"Former Yugoslav Republic of Macedonia", "France", "French Guiana",
"French Polynesia", "Macau", "Madagascar", "Malawi", "Malaysia",
"Maldives", "Mali", "Malta", "Marshall Islands", "Yemen",
"Yugoslavia", "Zambia", "Zimbabwe" };

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

// Sortin array
Arrays.sort(COUNTRY);

final ListView lv1 = (ListView) findViewById(R.id.ListView);
lv1.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, COUNTRY));
mGestureDetector = new GestureDetector(this, new SideIndexGestureListener());
}

@Override
public boolean onTouchEvent(MotionEvent event)
{
if (mGestureDetector.onTouchEvent(event))
{
return true;
} else
{
return false;
}
}

private ArrayList<Object[]> createIndex(String[] strArr)
{
ArrayList<Object[]> tmpIndexList = new ArrayList<Object[]>();
Object[] tmpIndexItem = null;

int tmpPos = 0;
String tmpLetter = "";
String currentLetter = null;
String strItem = null;

for (int j = 0; j < strArr.length; j++)
{
strItem = strArr[j];
currentLetter = strItem.substring(0, 1);

// every time new letters comes
// save it to index list
if (!currentLetter.equals(tmpLetter))
{
tmpIndexItem = new Object[3];
tmpIndexItem[0] = tmpLetter;
tmpIndexItem[1] = tmpPos - 1;
tmpIndexItem[2] = j - 1;

tmpLetter = currentLetter;
tmpPos = j + 1;

tmpIndexList.add(tmpIndexItem);
}
}

// save also last letter
tmpIndexItem = new Object[3];
tmpIndexItem[0] = tmpLetter;
tmpIndexItem[1] = tmpPos - 1;
tmpIndexItem[2] = strArr.length - 1;
tmpIndexList.add(tmpIndexItem);

// and remove first temporary empty entry
if (tmpIndexList != null && tmpIndexList.size() > 0)
{
tmpIndexList.remove(0);
}

return tmpIndexList;
}

@Override
public void onWindowFocusChanged(boolean hasFocus)
{
super.onWindowFocusChanged(hasFocus);

final ListView listView = (ListView) findViewById(R.id.ListView);
LinearLayout sideIndex = (LinearLayout) findViewById(R.id.sideIndex);
sideIndexHeight = sideIndex.getHeight();
sideIndex.removeAllViews();


TextView tmpTV = null;

// we'll create the index list
indexList = createIndex(COUNTRY);


indexListSize = indexList.size();

// maximal number of item, which could be displayed
int indexMaxSize = (int) Math.floor(sideIndex.getHeight() / 20);

int tmpIndexListSize = indexListSize;

// handling that case when indexListSize > indexMaxSize
while (tmpIndexListSize > indexMaxSize)
{
tmpIndexListSize = tmpIndexListSize / 2;
}

// computing delta (only a part of items will be displayed to save a
// place)
double delta = indexListSize / tmpIndexListSize;

String tmpLetter = null;
Object[] tmpIndexItem = null;

// show every m-th letter
for (double i = 1; i <= indexListSize; i = i + delta)
{
tmpIndexItem = indexList.get((int) i - 1);
tmpLetter = tmpIndexItem[0].toString();
tmpTV = new TextView(this);
tmpTV.setText(tmpLetter);
tmpTV.setGravity(Gravity.CENTER);
tmpTV.setTextSize(20);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1);
tmpTV.setLayoutParams(params);
sideIndex.addView(tmpTV);
}

// and set a touch listener for it
sideIndex.setOnTouchListener(new OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
// now you know coordinates of touch
sideIndexX = event.getX();
sideIndexY = event.getY();

// and can display a proper item it country list
displayListItem();

return false;
}
});
}

class SideIndexGestureListener extends
GestureDetector.SimpleOnGestureListener
{
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY)
{
// we know already coordinates of first touch
// we know as well a scroll distance
sideIndexX = sideIndexX - distanceX;
sideIndexY = sideIndexY - distanceY;

// when the user scrolls within our side index
// we can show for every position in it a proper
// item in the country list
if (sideIndexX >= 0 && sideIndexY >= 0)
{
displayListItem();
}

return super.onScroll(e1, e2, distanceX, distanceY);
}
}

public void displayListItem()
{
// compute number of pixels for every side index item
double pixelPerIndexItem = (double) sideIndexHeight / indexListSize;

// compute the item index for given event position belongs to
int itemPosition = (int) (sideIndexY / pixelPerIndexItem);

// compute minimal position for the item in the list
int minPosition = (int) (itemPosition * pixelPerIndexItem);

// get the item (we can do it since we know item index)
Object[] indexItem = indexList.get(itemPosition);

// and compute the proper item in the country list
int indexMin = Integer.parseInt(indexItem[1].toString());
int indexMax = Integer.parseInt(indexItem[2].toString());
int indexDelta = Math.max(1, indexMax - indexMin);

double pixelPerSubitem = pixelPerIndexItem / indexDelta;
int subitemPosition = (int) (indexMin + (sideIndexY - minPosition) / pixelPerSubitem);

ListView listView = (ListView) findViewById(R.id.ListView);
listView.setSelection(subitemPosition);
}
}

------------------------------------------------------------------------------------------------------------------------------

2:-  main.xml




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

android:layout_height="wrap_content">
<ListView 
android:id="@+id/ListView" 
android:layout_width="0dp"
android:fastScrollEnabled="true"
android:layout_height="wrap_content" 
android:layout_weight="1">
</ListView>
<LinearLayout 
android:orientation="vertical"
android:background="#FFF" 
android:id="@+id/sideIndex"
android:layout_width="40dip" 
android:layout_height="fill_parent"
android:gravity="center_horizontal">
</LinearLayout>
</LinearLayout>
</LinearLayout>

------------------------------------------------------------------------------------------------------------------------------



3:- Manifiest file:- 



 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="de.helloandroid.sideindex"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name="andriod.abhi.sideindex.SideIndex"
                  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="3" />

</manifest> 

Customised ListView With Images

Custom ListView with images contains Custom Adapter that i have explained it in below examples:----
1:- CustomListView.java


package com.example.demo;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class CustomListView extends ListActivity {

ArrayList<String> listItems=new ArrayList<String>();

   //DEFINING STRING ADAPTER WHICH WILL HANDLE DATA OF LISTVIEW
//    ArrayAdapter<String> adapter;
MyPerformanceArrayAdapter adapter;
   //RECORDING HOW MUCH TIMES BUTTON WAS CLICKED
   int clickCounter=0;

   @Override
   public void onCreate(Bundle icicle) {
       super.onCreate(icicle);
       setContentView(R.layout.main);
        adapter=new MyPerformanceArrayAdapter(this,listItems);
       setListAdapter(adapter);
   }

   //METHOD WHICH WILL HANDLE DYNAMIC INSERTION
   public void addItems(View v) {
       listItems.add("Clicked : "+clickCounter++);
//    adapter.add(listItems.get(0));
   adapter.notifyDataSetChanged();
   }

   public class MyPerformanceArrayAdapter extends ArrayAdapter<String> {
     private final Activity context;
     private final ArrayList<String> names;

     
     public MyPerformanceArrayAdapter(Activity context, ArrayList<String> listItems) {
       super(context, R.layout.list_layout, listItems);
       this.context = context;
       this.names = listItems;
     }

     @Override
     public View getView(int position, View convertView, ViewGroup parent) {
       View rowView = convertView;
       if (rowView == null) {
         LayoutInflater inflater = context.getLayoutInflater();
         rowView = inflater.inflate(R.layout.list_layout, null);
         ViewHolder viewHolder = new ViewHolder();
         viewHolder.text = (TextView) rowView.findViewById(R.id.textview);
         viewHolder.image = (CheckBox) rowView
             .findViewById(R.id.checkbox);
         rowView.setTag(viewHolder);
       }

       ViewHolder holder = (ViewHolder) rowView.getTag();
       String s = names.get(position);
       holder.text.setText(s);
      
       return rowView;
     }
   
    class ViewHolder {
       public TextView text;
       public CheckBox image;
     }

}
------------------------------------------------------------------------------------------------------------
2:- main.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" >
    <Button
        android:id="@+id/addBtn"
        android:text="Add New Item"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="addItems"/>
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:drawSelectorOnTop="false"
    />
</LinearLayout>

----------------------------------------------------------------------------------------------------------

3:-  list_layout.xml:- 



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >
    
    <CheckBox 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/checkbox"/>
        <TextView 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="hello"
            android:id="@+id/textview"/>
            

</LinearLayout>

Sql Lite Databas in android


Android Fragment Life Cycle



onAttach:_  ( Activity) called once the fragment is associated with its activity.

onCreate():-

System calls this method while creating new fragment. If user want to remain essential componet while other methods call like onPause() or onResume() methods.
    
onCreateView():-
System calls this method when View to be added in activity or draw user interface for user view. it will return View from the method. if we return null, it will not show UI in application.
    









onActivityCreated(Bundle) :- tells the fragment that its activity has completed its own Activity.onCreate().

  onViewStateRestored(Bundle) :_ tells the fragment that all of the saved state of its view hierarchy has been restored.

onStart() :-makes the fragment visible to the user (based on its containing activity being started).

onResume() :- makes the fragment interacting with the user (based on its containing activity being resumed).
As a fragment is no longer being used, it goes through a reverse series of callbacks:


onPause():_It indicate that user leaves this fragment , but it is not going to destroyed. 

onStop() :- fragment is no longer visible to the user either because its activity is being stopped or a fragment operation is modifying it in the activity.

onDestroyView() :- allows the fragment to clean up resources associated with its View.

onDestroy() :- called to do final cleanup of the fragment's state.

onDetach() :- called immediately prior to the fragment no longer being associated with its activity.

    


BroadCast Receiver for Android


Wednesday, April 3, 2013

Android Activity Life Cycle



An activity is a user interaction screen that the user use the device at one time. An application can have multiple activities , and the user go back and among them. That's why activities are the most visible part of our application.

I usually use a website as an analogy for activities. Just like a website consists of multiple pages, so does an Android application consist of multiple activities. Just like a website has a “home page,” an Android app has a “main” activity, usually the one that is shown first when you launch the application. And just like a website has to provide some sort of navigation among various pages, an Android app should do the same.

for example: on the website, we can navigate from a page on one website to a page on another. Similarly, in Android, we look at an activity of an application, and navigate to another activity of an application in a completely separate application. For example, if you are in your Contacts app and you choose to text a friend, you’d be launching the activity to compose a text message in the Messaging application.

Launching an activity can be quite expensive. It may involve creating a new Linux process, allocating memory for all the UI objects, inflating all the objects from XML layouts, and setting up the whole screen. Since we’re doing a lot of work to launch an activity, it would be a waste to just toss it out once the user leaves that screen. To avoid this waste, the activity life cycle is managed via Activity Manager.

Activity Manager is responsible for creating, destroying, and managing activities. For example, when the user starts an application for the first time, the Activity Manager will create its activity and put it onto the screen. Later, when the user switches screens, the Activity Manager will move that previous activity to a holding place. This way, if the user wants to go back to an older activity, it can be started more quickly. Older activities that the user hasn’t used in a while will be destroyed in order to free more space for the currently active one. This mechanism is designed to help improve the speed of the user interface and thus improve the overall user experience.

Programming for Android is conceptually different than programming for some other environments. In Android, you find yourself responding more to certain changes in the state of your application rather than driving that change yourself. It is a managed, container-based environment similar to programming for Java applets or servlets. So, when it comes to an activity life cycle, you don’t get to say what state the activity is in, but you have plenty of opportunity to say what happens during the transitions from state to state. Figure 4-1 shows the states that an activity can go through.


Android operating system  have Java classes that  extended it's predefined classes with different method. Activity is also a predefined class that have predefined method. All method run sequentially by nature of life cycle . Activity is a class that represent UI part in android.  it have some sequential flow as per different conditions.

An activity is a user interaction screen that the user use the device at one time. An application can have multiple activities , and the user go back and among them. That's why activities are the most visible part of our application.

I usually use a website as an analogy for activities. Just like a website consists of multiple pages, so does an Android application consist of multiple activities. Just like a website has a “home page,” an Android app has a “main” activity, usually the one that is shown first when you launch the application. And just like a website has to provide some sort of navigation among various pages, an Android app should do the same.

for example: on the website, we can navigate from a page on one website to a page on another. Similarly, in Android, we look at an activity of an application, and navigate to another activity of an application in a completely separate application. For example, if you are in your Contacts app and you choose to text a friend, you’d be launching the activity to compose a text message in the Messaging application.

Launching an activity can be quite expensive. It may involve creating a new Linux process, allocating memory for all the UI objects, inflating all the objects from XML layouts, and setting up the whole screen. Since we’re doing a lot of work to launch an activity, it would be a waste to just toss it out once the user leaves that screen. To avoid this waste, the activity life cycle is managed via Activity Manager.

Activity Manager is responsible for creating, destroying, and managing activities. For example, when the user starts an application for the first time, the Activity Manager will create its activity and put it onto the screen. Later, when the user switches screens, the Activity Manager will move that previous activity to a holding place. This way, if the user wants to go back to an older activity, it can be started more quickly. Older activities that the user hasn’t used in a while will be destroyed in order to free more space for the currently active one. This mechanism is designed to help improve the speed of the user interface and thus improve the overall user experience.





 For Activity We have to know first  What is an Activity?

An activity is a user interaction screen that the user use the device at one time. An application can have multiple activities , and the user go back and among them. That's why activities are the most visible part of our application.
Activity represents the view part of android with the use of different methods to show and upload the user interface.


 android activity life cycle method sequence are below:


                                               1:-  onCreate();
                                               
                                               2:- onStart();    or   onRestart();
                                               
                                               3:- onResume();

                                               4:- onPause();

                                               5:- onStop();

                                               6:- onDestroy();


1:- onCreate():-


When an activity doesn’t exist in memory, it is in a starting state. While it’s starting up, the activity will go through a whole set of callback methods that you as a developer have an opportunity to fill out. Eventually, the activity will be in a running state.

Keep in mind that this transition from starting state to running state is one of the most expensive operations in terms of computing time, and this also directly affects the battery life of the device. This is the exact reason why we don’t automatically destroy activities that are no longer shown. The user might want to come back to them, so we keep them around for a while.



In Android Activity Life Cycle, this method Called when the activity is first created. Android first method of life cycle is onCreate(), it has parameter Bundle type named as savedInstanceState. that contains bundle information send by previous activity. it will register all the views and bind data to lists.

2:- onRestart():-

The activity in a running state is the one that is currently on the screen and interacting with the user. We also say this activity is in focus, meaning that all user interactions—such as typing, touching the screen, and clicking buttons—are handled by this one activity. As such, there is only one running activity at any given time.

The running activity is the one that has priority in terms of getting the memory and resources it needs to run as quickly as possible. This is because Android wants to make sure the running activity is zippy and responsive to the user.


In Android Activity Life Cycle, this method called after your activity has been stopped,  it being started again. Always followed by onStart().
 
2:- onStart():-  In Android Activity Life Cycle, this method Android Acitvity now starting all Views to visualisation state for all the Views. and it will now proceed to onResume() Method.

3:- onResume():-In Android Activity Life Cycle, this method is called With in this state Activity goes in  foreground and the user can interact with it.


4:- onPause():-  When an activity is not in focus (i.e., not interacting with the user) but still visible on the screen, we say it’s in a paused state. This is not a typical scenario, because the device’s screen is usually small, and an activity is either taking up the whole screen or none at all. We often see this case with dialog boxes that come up in front of an activity, causing it to become Paused. All activities go through a paused state en route to being stopped.

Paused activities still have high priority in terms of getting memory and other resources. This is because they are visible and cannot be removed from the screen without making it look very strange to the user.


In Android Activity Life Cycle, this method called When user call another activity by present activity then it will goes onPause() State.
it will be onPause() state untill it shows up.

5:- onStop():-  When an activity is not visible, but still in memory, we say it’s in a stopped state. Stopped activity could be brought back to the front to become a Running activity again. Or, it could be destroyed and removed from memory.

The system keeps activities around in a stopped state because it is likely that the user will still want to get back to those activities some time soon, and restarting a stopped activity is far cheaper than starting an activity from scratch. That is because we already have all the objects loaded in memory and simply have to bring it all up to the foreground.

Stopped activities can be removed from memory at any point.


In Android Activity Life Cycle, this method is called When activity No Longer Visible and not called then the activtiy goes onStop() State.
we will next receive either onRestart(), onDestroy(), or nothing, depending on later user activity.

6:- onDestroy():- A destroyed activity is no longer in memory. The Activity Manager decided that this activity is no longer needed and has removed it. Before the activity is destroyed, it can perform certain actions, such as save any unsaved information. However, there’s no guarantee that your activity will be stopped prior to being destroyed. It is possible for a paused activity to be destroyed as well. For that reason, it is better to do important work, such as saving unsaved data, en route to a paused state rather than a destroyed state.
In Android Activity Life Cycle, this method called Activty goes destroy State when it will got any error or get closed. this can also be happed when the system is temporarily destroying this instance of the activity to save space.



When Activity first Time load below methods called:-

----> onCreate()
----> onStart()
----> onResume()
 
When We go to another Activity Then below Methods Called.
 
---> onPause()
---> onStop() 
When returning from Second Activity to First Acitvity then below Methods Called.

---> onRestart()
---> onStart()
---> onResume()
 
When we exit from Application these methods Called
 
---> onPause()
---> onStop()
---> onDestroy() 





Activity Life Cycle  sequence are below: --



Image
for more detail go to http://developer.android.com/training/basics/activity-lifecycle/index








Example for Activity Life Cycle:------------



package com.android.demo;

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

public class ActivityA exends  Activity{
   
    Button btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        Toast.makeText(this, "create", 2000).show();
Button btn  =(Button)findViewById(R.id.btn);
        btn.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent intent  = new Intent(this, AcitivityB.class);
                startActivity(intent);
            }
        });
       
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        Toast.makeText(this, "start", 2000).show();

    }
   
    @Override
    protected void onRestart() {
        // TODO Auto-generated method stub
        super.onRestart();
        Toast.makeText(this, "restart", 2000).show();

    }
   
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        Toast.makeText(this, "resume", 2000).show();

    }
   
    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        Toast.makeText(this, "pause", 2000).show();

    }
   
    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        Toast.makeText(this, "pause", 2000).show();

    }
   
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        Toast.makeText(this, "destroy", 2000).show();

    }
   
}


/////////////////////////////////  Activity B//////////////////////////////////////////////

package com.android.demo;

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

public class ActivityB exends  Activity{
   
      @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        Toast.makeText(this, "create", 2000).show();

       
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        Toast.makeText(this, "start", 2000).show();

    }
   
    @Override
    protected void onRestart() {
        // TODO Auto-generated method stub
        super.onRestart();
        Toast.makeText(this, "restart", 2000).show();

    }
   
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        Toast.makeText(this, "resume", 2000).show();

    }
   
    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        Toast.makeText(this, "pause", 2000).show();

    }
   
    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        Toast.makeText(this, "pause", 2000).show();

    }
   
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        Toast.makeText(this, "destroy", 2000).show();

    }
   
}