View

Thursday, 8 September 2011

Phone internal and External storage usage

How to check Phone internal/external memory usage using programmatically in android

Android have a default API to check the phone internal and external memory usage.In My application
i used both as well as memory informations.The internal and external both are same,just to change
the Environment path.
Internal=StatFs stat=new StatFs(Environment.getDataDirectory().getPath());
External=StatFs stat=new StatFs(Environment.getExternalStorageDirectory().getPath());
The user can just hit the seek bar its show the occupied space in bytes,availabel space in MB,
Before that first to create new emulatore with size can set it in Kb or MB.I used 24MB.
public class Internal_Storage extends Activity  implements SeekBar.OnSeekBarChangeListener{
 SeekBar sb;
 int progress;
 Boolean value=false;
 Button press_btn;
 TextView availabel_in_tv,occupied_in_tv,tv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.internal_storage);
        availabel_in_tv=(TextView)findViewById(R.id.availabel_in_tv);
        occupied_in_tv=(TextView)findViewById(R.id.occupied_in_tv);
        final TextView reading = (TextView) findViewById(R.id.textView1);
        sb = (SeekBar)findViewById(R.id.sb);
        sb.setMax(100);
    @Override
    public void onProgressChanged(SeekBar seekBar, int size, boolean fromtouch) {
        reading.setText("Loading "+size+"% ");
        method1();
       
        }
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
       
        }
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
    }
  });
    }
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
    }
 @Override
 public void onStartTrackingTouch(SeekBar seekBar) {
  // TODO Auto-generated method stub

 }
 @Override
 public void onStopTrackingTouch(SeekBar seekBar) {
  // TODO Auto-generated method stub
 }
public String method1(){
StatFs stat=new StatFs(Environment.getDataDirectory().getPath()); //**ITS show  phone internal  storage size**//
       or
StatFs stat=new StatFs(Environment.getExternalStorageDirectory().getPath());  //**ITS show  phone SD card storage size**//

    int blockSize = stat.getBlockSize();
    int availableBlocks = stat.getAvailableBlocks();     
    System.out.println("statFs:"+"=" +stat);
    System.out.println("SPACE AVAILABEL :"+"=" +availableBlocks);
     //occup_size_tv.setTextSize(availableBlocks);
     occupied_in_tv.setText(Integer.toString(availableBlocks));
     System.out.println("SIZE OCCUPY:"+"=" +blockSize);
  
     availabel_in_tv.setText((Formatter.formatFileSize(this,availableBlocks*blockSize)));
     System.out.println("FREE SPACE:="+Formatter.formatFileSize(this,availableBlocks*blockSize));
     System.out.println("FREE SPACE IN BYTES:"+availableBlocks +1042.f*1024.f);
     // bytesAvailable / (1024.f * 1024.f);
     return Formatter.formatShortFileSize(this, availableBlocks * blockSize);


 }
the same code repeated for internal and external.class
Then next class Memory_Information.class,its show total memory usage details
public class Memory_Information extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.memory_information);   
        TextView CPUinfo = (TextView) findViewById(R.id.textView1);
        CPUinfo.setText(ReadCPUinfo());    
    }
    private String ReadCPUinfo()
    {
     ProcessBuilder cmd;
   
     StringBuffer strMemory = new StringBuffer();
     //final ActivityManager activityManager =(ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
   
     ActivityManager actvityManager = (ActivityManager) this.getSystemService( ACTIVITY_SERVICE );
     ActivityManager.MemoryInfo mInfo = new ActivityManager.MemoryInfo ();
     actvityManager.getMemoryInfo( mInfo );
   
     strMemory.append("Available Memory : ");
     strMemory.append(mInfo.availMem);
     strMemory.append("\n");
     strMemory.append("\n");
   
     String result=strMemory.toString();
   
     try{
      String[] args = {"/system/bin/cat", "/proc/meminfo"};
      cmd = new ProcessBuilder(args);
   
      Process process = cmd.start();
      InputStream in = process.getInputStream();
      byte[] re = new byte[1024];
      while(in.read(re) != -1){
       System.out.println(new String(re));
       result = result + new String(re);
      }
      in.close();
     } catch(IOException ex){
      ex.printStackTrace();
     }
     return result;
    }
}
you may check in console also or u can clarify the usage in phones settings. go to settings/SD card & phone storage/


How to check Phone internal/external memory usage using programmatically in android

Android have a default API to check the phone internal and external memory usage.In My application
i used both as well as memory informations.The internal and external both are same,just to change
the Environment path.
Internal=StatFs stat=new StatFs(Environment.getDataDirectory().getPath());
External=StatFs stat=new StatFs(Environment.getExternalStorageDirectory().getPath());
The user can just hit the seek bar its show the occupied space in bytes,availabel space in MB,
Before that first to create new emulatore with size can set it in Kb or MB.I used 24MB.
public class Internal_Storage extends Activity  implements SeekBar.OnSeekBarChangeListener{
 SeekBar sb;
 int progress;
 Boolean value=false;
 Button press_btn;
 TextView availabel_in_tv,occupied_in_tv,tv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.internal_storage);
        availabel_in_tv=(TextView)findViewById(R.id.availabel_in_tv);
        occupied_in_tv=(TextView)findViewById(R.id.occupied_in_tv);
        final TextView reading = (TextView) findViewById(R.id.textView1);
        sb = (SeekBar)findViewById(R.id.sb);
        sb.setMax(100);
    @Override
    public void onProgressChanged(SeekBar seekBar, int size, boolean fromtouch) {
        reading.setText("Loading "+size+"% ");
        method1();
       
        }
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
       
        }
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
    }
  });
    }
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
    }
 @Override
 public void onStartTrackingTouch(SeekBar seekBar) {
  // TODO Auto-generated method stub

 }
 @Override
 public void onStopTrackingTouch(SeekBar seekBar) {
  // TODO Auto-generated method stub
 }
public String method1(){
StatFs stat=new StatFs(Environment.getDataDirectory().getPath()); //**ITS show  phone internal  storage size**//
       or
StatFs stat=new StatFs(Environment.getExternalStorageDirectory().getPath());  //**ITS show  phone SD card storage size**//

    int blockSize = stat.getBlockSize();
    int availableBlocks = stat.getAvailableBlocks();     
    System.out.println("statFs:"+"=" +stat);
    System.out.println("SPACE AVAILABEL :"+"=" +availableBlocks);
     //occup_size_tv.setTextSize(availableBlocks);
     occupied_in_tv.setText(Integer.toString(availableBlocks));
     System.out.println("SIZE OCCUPY:"+"=" +blockSize);
  
     availabel_in_tv.setText((Formatter.formatFileSize(this,availableBlocks*blockSize)));
     System.out.println("FREE SPACE:="+Formatter.formatFileSize(this,availableBlocks*blockSize));
     System.out.println("FREE SPACE IN BYTES:"+availableBlocks +1042.f*1024.f);
     // bytesAvailable / (1024.f * 1024.f);
     return Formatter.formatShortFileSize(this, availableBlocks * blockSize);


 }
the same code repeated for internal and external.class
Then next class Memory_Information.class,its show total memory usage details
public class Memory_Information extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.memory_information);   
        TextView CPUinfo = (TextView) findViewById(R.id.textView1);
        CPUinfo.setText(ReadCPUinfo());    
    }
    private String ReadCPUinfo()
    {
     ProcessBuilder cmd;
   
     StringBuffer strMemory = new StringBuffer();
     //final ActivityManager activityManager =(ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
   
     ActivityManager actvityManager = (ActivityManager) this.getSystemService( ACTIVITY_SERVICE );
     ActivityManager.MemoryInfo mInfo = new ActivityManager.MemoryInfo ();
     actvityManager.getMemoryInfo( mInfo );
   
     strMemory.append("Available Memory : ");
     strMemory.append(mInfo.availMem);
     strMemory.append("\n");
     strMemory.append("\n");
   
     String result=strMemory.toString();
   
     try{
      String[] args = {"/system/bin/cat", "/proc/meminfo"};
      cmd = new ProcessBuilder(args);
   
      Process process = cmd.start();
      InputStream in = process.getInputStream();
      byte[] re = new byte[1024];
      while(in.read(re) != -1){
       System.out.println(new String(re));
       result = result + new String(re);
      }
      in.close();
     } catch(IOException ex){
      ex.printStackTrace();
     }
     return result;
    }
}
you may check in console also or u can clarify the usage in phones settings. go to settings/SD card & phone storage/
 
  



Wednesday, 17 August 2011

How to create contextmenu in android

creating a context menu is very simple,Here i use Textview name as press me on long,when the textview is pressed for long,its open a context menu.In that context menu i use New,edit,copy,paste and delete.
Inside of the onCreate Method,we have to registerForcontextmenu(controls name)
Example: press=(TextView)findViewById(R.id.press_tv);
               registerForContextMenu(press); 
Then we  need to override the onCreateContextMenu method to create the menu:
 @Override 
   public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {  
  super.onCreateContextMenu(menu, v, menuInfo);  
   menu.setHeaderTitle("Context Menu");  
   menu.add(0, v.getId(), 0, "New");  
   menu.add(0, v.getId(), 0, "Edit");  
   menu.add(0, v.getId(), 0, "copy");  
   menu.add(0, v.getId(), 0, "Paste");  
   menu.add(0, v.getId(), 0, "Delete");  
when the item is selected,that items action can perform here,using onContextItemSelected method.
Here i use function for only "New" just passing the Intent,If u want some functions mean, you write a else if () and perform some more actions there.
 @Override 
  public boolean onContextItemSelected(MenuItem item) {  
   if(item.getTitle()=="New"){
    Intent np=new Intent(getApplicationContext(),NewPage.class);
    startActivity(np);
    function1(item.getItemId());}  
   else if(item.getTitle()=="Save"){
    //Some funtion perform here//
    function2(item.getItemId());}  
    else {return false;}  
  return true;  
 }
create a method for function1.... function n,
private void function2(int itemId) {
  // TODO Auto-generated method stub
 
 }
 private void function1(int itemId) {
  // TODO Auto-generated method stub
 
 } 
Result is:
           

pic1

pic2

 
  

pic3

pic4
Download full source code 

Friday, 5 August 2011

How to create FeedBack Form inside of the customDialogBox?

How to create a form in dialog box,Here i use sample feed back form inside of the custom dialogbox,First u have to create a button in main.xml file,Because when the button is press ,FeedBack Form can open in customdialogbox,so thats why i had put a Button(Press Dialog).After that you also create a new xml file name as dialog.xml,In that xml ,i use Name,Mail,Comment and two buttons like send and cancel.
code for dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:orientation="vertical" android:layout_height="wrap_content">
    <LinearLayout android:id="@+id/linearLayout1" android:layout_height="wrap_content" android:layout_width="match_parent">
        <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Name" android:textSize="15dp" android:layout_marginLeft="10dp" android:layout_marginTop="5dp"></TextView>
        <EditText android:id="@+id/editText1" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:layout_width="200dp" android:layout_marginLeft="16dp"></EditText>
    </LinearLayout>
    <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/linearLayout2">
        <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Mail Id:" android:layout_marginTop="5dp" android:layout_marginLeft="5dp"></TextView>
        <EditText android:id="@+id/editText2" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:layout_width="200dp" android:layout_marginLeft="16dp"></EditText>
    </LinearLayout>
    <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/linearLayout3">
        <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Comment" android:layout_marginLeft="5dp" android:layout_marginTop="5dp"></TextView>
        <EditText android:id="@+id/editText3" android:layout_height="100dp" android:layout_width="200dp"></EditText>
    </LinearLayout>
    <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/linearLayout4">
        <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Send" android:layout_marginLeft="70dp"></Button>
        <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Cancel"></Button>
    </LinearLayout>
</LinearLayout>
Then i have to create a main class name as FeedbackFormusingInsideDialogBox.java
static final int CUSTOM_DIALOG_ID = 0;
Button customDialog_Dismiss;
The class have to declare as a
its a very few line code to creat a dialogbox.Just button press click listener,Dialog onCreateDialog and cancel button listener.
here i put full code .just check it

public class FeedbackFormusingInsideDialogBox extends Activity {
 static final int CUSTOM_DIALOG_ID = 0;
 Button customDialog_Dismiss;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);      
        Button buttonStartDialog = (Button)findViewById(R.id.startdialog);
        buttonStartDialog.setOnClickListener(new Button.OnClickListener(){
   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    showDialog(CUSTOM_DIALOG_ID);
   }
        });
              
    }     
    private Button.OnClickListener customDialog_DismissOnClickListener  = new Button.OnClickListener(){ 
  @Override
  public void onClick(View arg0) {
   // TODO Auto-generated method stub
   dismissDialog(CUSTOM_DIALOG_ID);
  }    
    };   
 @Override
 protected Dialog onCreateDialog(int id) {
  // TODO Auto-generated method stub
  Dialog dialog = null;;
     switch(id) {
     case CUSTOM_DIALOG_ID:
      dialog = new Dialog(this);
      dialog.setContentView(R.layout.dialogbox);
      dialog.setTitle("Feed Back Form");
             customDialog_Dismiss = (Button)dialog.findViewById(R.id.button2);
             customDialog_Dismiss.setOnClickListener(customDialog_DismissOnClickListener);
         break;
     }
     return dialog;
 } 
 }
Result :




Tuesday, 2 August 2011

How to use swipe in android?

Swipe is otherwise called  as a Fling. Its a touch free movement in android.
Before that we have set some SWIPE MIN,MAX Distance,Threshold_velosity and as well as path.
 private static final int SWIPE_MIN_DISTANCE = 120;
  private static final int SWIPE_MAX_OFF_PATH = 250;
 private static final int SWIPE_THRESHOLD_VELOCITY = 200;
 private GestureDetector gestureDetector;
 View.OnTouchListener gestureListener;
 private Animation slideLeftIn;
 private Animation slideLeftOut;
 private Animation slideRightIn;
        private Animation slideRightOut;
        private ViewFlipper viewFlipper;
Next step is to write a code inside of the onCreate Method
        setContentView(R.layout.main);
        viewFlipper = (ViewFlipper)findViewById(R.id.flipper);
        slideLeftIn = AnimationUtils.loadAnimation(this, R.anim.slide_left_in);
        slideLeftOut = AnimationUtils.loadAnimation(this, R.anim.slide_left_out);
        slideRightIn = AnimationUtils.loadAnimation(this, R.anim.slide_right_in);
        slideRightOut = AnimationUtils.loadAnimation(this, R.anim.slide_right_out);
       
        gestureDetector = new GestureDetector(new MyGestureDetector());
        gestureListener = new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if (gestureDetector.onTouchEvent(event)) {
                    return true;
                }
                return false;
            }
        };
You will need to extend SimpleOnGestureListener to implement your own handling on swipe/fling action:

 class MyGestureDetector extends SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            try {
                if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                    return false;
                // right to left swipe
                if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                 viewFlipper.setInAnimation(slideLeftIn);
                    viewFlipper.setOutAnimation(slideLeftOut);
                 viewFlipper.showNext();
                }  else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                 viewFlipper.setInAnimation(slideRightIn);
                    viewFlipper.setOutAnimation(slideRightOut);
                 viewFlipper.showPrevious();
                }
            } catch (Exception e) {
                // nothing
            }
            return false;
        }
    }
At last, you need to make sure in your activity, you catch the gesture event by overriding onTouch() method:
 
@Override
    public boolean onTouchEvent(MotionEvent event) {
        if (gestureDetector.onTouchEvent(event))
         return true;
     else
      return false;
    }
Here i use viewflipper,two LinearLayouts and two Buttons in main.xml file you have to set as <ViewFlipper xmlns:android="http://......" like this

<?xml version="1.0" encoding="utf-8"?>
<ViewFlipper xmlns:android="http://schemas.android.com/apk/res/android"
     android:id="@+id/flipper"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent">
   
 <LinearLayout
  android:layout_width="fill_parent" android:layout_height="70dp" android:background="#E2A9F3">
  <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="30dp" android:layout_marginTop="10dp" android:text="Swipe Me" android:textSize="20dp" android:textColor="#DF0101"></TextView>
    </LinearLayout>  
    <LinearLayout
  android:layout_width="fill_parent" android:layout_height="60dp" android:background="#585858">
     <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Back"></Button>
     <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Next"></Button>
    </LinearLayout>  
</ViewFlipper>
At last thing u have to create a new folder and set name as anim or what u wish ,u give it.In that folder you have to  create a xml for Left_in,Left_out,Right_in and right_out and set the values.
name:slide_left_in.xml
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="100%p" android:toXDelta="0" android:duration="800"/>
</set>
name:slide_left_out.xml
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="0" android:toXDelta="-100%p" android:duration="800"/>
</set>
name:slide_right_in.xml
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="-100%p" android:toXDelta="0" android:duration="800"/>
</set>
name:slide_right_out.xml
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="0" android:toXDelta="100%p" android:duration="800"/>
</set>

Result:
 

Monday, 1 August 2011

How to use Menu Option in Android?

Its a very simple way to use menu option in android, just only four line to write it. first u have to  create new folder and name as menu
example res/menu/sample.xml.
give some options what u want ,Here i gave file,open,save and edit

<?
<
xml version="1.0" encoding="utf-8"?>menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/file" android:title="@string/file" />
<item android:id="@+id/open" android:title="@string/open"/> <item android:id="@+id/save" android:title="@string/save" />
<item android:id="@+id/edit" android:title="@string/edit"/> </menu>
after that we have to set a values in strings.xml
example:values/strings.xml
<?
<
xml version="1.0" encoding="utf-8"?>resources>
<string name="hello">Hello World, MenuScreen!</string>
<string name="app_name">SampleMenu</string>
<string name="file">File</string>
<string name="open">Open</string>
<string name="save">Save</string>
</
<string name="edit">Edit</string>resources>
now you have to write a code to show the menu options.
@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.sample, menu);         
        return true;
    }
Result is:

Thursday, 7 July 2011

How to use Multi Language in android?

How to use multi language of text in android?

Its just a easy way to use it.How ? The html decimal unicode is suppoted by android os.Here i show three languages,Tamil,hindi and Telungu.First of all u should download the DLL file.For example :
"Akshar.ttf",Its a one of the Library file,It help to convert the decimal unicode format.Your Android application there is assests folder ,you just create a new folder and name as fonts,then put inside of the "Akshar.ttf" file in that folder,Now come to our Code section.

 TextView english,tamil,hin,tel;
String tam,h,t;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tamil=(TextView)findViewById(R.id.textView2);
        hin=(TextView)findViewById(R.id.hindi);
        tel=(TextView)findViewById(R.id.telngu);
        tam="&#3000;&#2965;&#45;&#2949;&#2985;&#3021;&#2975;&#3021;&#2992;&#3018;&#2951;&#2975;&#3021; &#2949;&#2986;&#3021;&#2986;&#3021;&#2994;&#3007;&#2965;&#2975;&#3007;&#2962;&#2985;&#3021;&#46;&#2986;&#3021;&#2994;&#3018;&#2965;&#3021;&#3000;&#3021;&#2986;&#3018;&#2975;&#3021;&#46;&#2965;&#3018;&#2990;&#3021;";
        h="&#2360;&#2327;&#45;&#2309;&#2344;&#2381;&#2337;&#2381;&#2352;&#2379;&#2311;&#2337;&#2381; &#2309;&#2346;&#2381;&#2346;&#2381;&#2354;&#2367;&#99;&#2309;&#2335;&#2367;&#2323;&#2344;&#2381;&#46;&#2348;&#2381;&#2354;&#2379;&#2327;&#2381;&#2360;&#2381;&#2346;&#2379;&#2335;&#2381;&#46;&#99;&#2323;&#2350;&#2381;";
        t="&#3128;&#3095;&#45;&#3077;&#3112;&#3149;&#3105;&#3149;&#3120;&#3146;&#3079;&#3105;&#3149; &#3077;&#3114;&#3149;&#3114;&#3149;&#3122;&#3135;&#99;&#3077;&#3103;&#3135;&#3090;&#3112;&#3149;&#46;&#3116;&#3149;&#3122;&#3146;&#3095;&#3149;&#3128;&#3149;&#3114;&#3146;&#3103;&#3149;&#46;&#99;&#3090;&#3118;&#3149;        ";
       
        Typeface tf=Typeface.createFromAsset(getAssets(), "fonts/Akshar.ttf");
       
      
        tamil.setTypeface(tf,Typeface.BOLD);
        tamil.setText(Html.fromHtml(tam));
       
        hin.setTypeface(tf,Typeface.ITALIC);
        hin.setText(Html.fromHtml(h));
       
       
        tel.setTypeface(tf,Typeface.NORMAL);
        tel.setText(Html.fromHtml(t));
       
    }
}


The output is:
Download full source code

Saturday, 2 July 2011

How to use Autocomplete searchbox in Database?

Autocomplete means it show the complete text automatically.It have two types
1.Single line autocomplete
2.Multi line autocomplete
what letter we type in the searchbox,that letter of the complete words  to show.Here i use autocomplete searchbox ,The select item can pass into the textview
.I use DATABASE NAME as="itemsearchsqlite.db",TABLE NAME as="itemsearch" and DB COLUMN NAME as="item_name".
I use two java classes namely Home.java and SQLiteItemsearch.java
//SQLiteItemSearch.java//
------------------------
package com.autocomplete.sample;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class SQLiteItemSearch extends SQLiteOpenHelper
{
    private static final String DB_NAME = "itemsearchsqlite.db";
    private static final int DB_VERSION_NUMBER = 1;
    private static final String DB_TABLE_NAME = "itemsearch";
    private static final String DB_COLUMN_1_NAME = "item_name";

    private static final String DB_CREATE_SCRIPT = "create table " + DB_TABLE_NAME +
                            " (_id integer primary key autoincrement, item_name text not null);)";

    private SQLiteDatabase sqliteDBInstance = null;

    public SQLiteItemSearch(Context context)
    {
        super(context, DB_NAME, null, DB_VERSION_NUMBER);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        // TODO: Implement onUpgrade
    }

    @Override
    public void onCreate(SQLiteDatabase sqliteDBInstance)
    {
        Log.i("onCreate", "Creating the database...");
        sqliteDBInstance.execSQL(DB_CREATE_SCRIPT);
    }

    public void openDB() throws SQLException
    {
        Log.i("openDB", "Checking sqliteDBInstance...");
        if(this.sqliteDBInstance == null)
        {
            Log.i("openDB", "Creating sqliteDBInstance...");
            this.sqliteDBInstance = this.getWritableDatabase();
        }
    }

    public void closeDB()
    {
        if(this.sqliteDBInstance != null)
        {
            if(this.sqliteDBInstance.isOpen())
                this.sqliteDBInstance.close();
        }
    }

    public long insertitmSearch(String ItemBrandName)
    {
        ContentValues contentValues = new ContentValues();
        contentValues.put(DB_COLUMN_1_NAME, ItemBrandName);
        Log.i(this.toString() + " - insertitmSearch", "Inserting: " + ItemBrandName);
        return this.sqliteDBInstance.insert(DB_TABLE_NAME, null, contentValues);
    }

    public boolean removeitmSearch(String ItemBrandName)
    {
        int result = this.sqliteDBInstance.delete(DB_TABLE_NAME, "item_name='" + ItemBrandName + "'", null);

        if(result > 0)
            return true;
        else
            return false;
    }

    public long updateitmSearch(String oldItemBrandName, String newItemBrandName)
    {
        ContentValues contentValues = new ContentValues();
        contentValues.put(DB_COLUMN_1_NAME, newItemBrandName);
        return this.sqliteDBInstance.update(DB_TABLE_NAME, contentValues, "item_name='" + oldItemBrandName + "'", null);
    }

    public String[] getAllItemFilter()
    {
        Cursor cursor = this.sqliteDBInstance.query(DB_TABLE_NAME, new String[] {DB_COLUMN_1_NAME}, null, null, null, null, null);

        if(cursor.getCount() >0)
        {
            String[] str = new String[cursor.getCount()];
            int i = 0;

            while (cursor.moveToNext())
            {
                 str[i] = cursor.getString(cursor.getColumnIndex(DB_COLUMN_1_NAME));
                 i++;
             }
            return str;
        }
        else
        {
            return new String[] {};
        }
    }
}

Then again we have to insert a rows of dataitems inside of the Home.java class
public class Home extends Activity {
 private SQLiteItemSearch sqllitebb;
 TextView tv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_item);
       
        final AutoCompleteTextView actv=(AutoCompleteTextView)findViewById(R.id.autocompleteitem);
        sqllitebb=new SQLiteItemSearch(Home.this);
        sqllitebb.openDB();
     // Insert a few item list statically//
     
        sqllitebb.insertitmSearch("Color Monitor");
        sqllitebb.insertitmSearch("Compact Disk");
        sqllitebb.insertitmSearch("Computer");
       sqllitebb.insertitmSearch("Copy Righter");
       sqllitebb.insertitmSearch("Hard Disk");
       sqllitebb.insertitmSearch("HP Printer");
       sqllitebb.insertitmSearch("HP Laser Printer");
       sqllitebb.insertitmSearch("HP Injet Printer");
      //  sqllitebb.removeitmsearch("Computer");
       // sqllitebb.updateitmSearch("Computer","DELL");
     final  String[] deal = sqllitebb.getAllItemFilter();
      
       // Print out the values to the log
       for(int i = 0; i < deal.length; i++)
       {
           Log.i(this.toString(), deal[i]);
       }
       ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,deal);
       actv.setAdapter(adapter); 
       actv.setThreshold(1);
       actv.setOnItemClickListener(new OnItemClickListener() {
           public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            tv=(TextView)findViewById(R.id.selecteditem_tv);
            tv.setText(deal[arg2]);
            arg0.getItemAtPosition(arg2);
                Log.i("SELECTED TEXT WAS------->",  deal[arg2]);
           }
       });
    }
    public void onDestroy()
    {
        super.onDestroy();
        sqllitebb.close();
    }
}

Wednesday, 1 June 2011

How to send and receive message using in android

I take a look at how  can programmatically send and receive SMS messages in our Android applications. The good news for Android developers is that we don't need a real device to test out SMS messaging - the free Android emulator provides the capability to do so.

In the 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"
    >
    <TextView 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Enter the phone number of recipient"
        />    
    <EditText
        android:id="@+id/txtPhoneNo" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"       
        />
    <TextView 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"        
        android:text="Message"
        />    
    <EditText
        android:id="@+id/txtMessage" 
        android:layout_width="fill_parent"
        android:layout_height="150px"
        android:gravity="top"        
        />         
    <Button
        android:id="@+id/btnSendSMS" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Send SMS"
        />   
</LinearLayout>

Next, in the SMS activity, we wire up the Button view so that when the user clicks on it, we will check to see that the phone number of the recipient and the message is entered before we send the message using the sendSMS() function, which we will define shortly:

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class SMS extends Activity {
    /** Called when the activity is first created. */
  Button btnSendSMS;
     EditText txtPhoneNo;
     EditText txtMessage;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
        txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
        txtMessage = (EditText) findViewById(R.id.txtMessage);

        btnSendSMS.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {               
                String phoneNo = txtPhoneNo.getText().toString();
                String message = txtMessage.getText().toString();                
                if (phoneNo.length()>0 && message.length()>0)               
                    sendSMS(phoneNo, message);               
                else
                    Toast.makeText(getBaseContext(),
                        "Please enter both phone number and message.",
                        Toast.LENGTH_SHORT).show();
            }

        });       
    }
 public void sendSMS(String phoneNo, String message) {
  String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";

        PendingIntent sentPI = PendingIntent.getBroadcast(getApplicationContext(), 0,
            new Intent(SENT), 0);

        PendingIntent deliveredPI = PendingIntent.getBroadcast(getApplicationContext(), 0,
            new Intent(DELIVERED), 0);

        //---when the SMS has been sent---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS sent",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Generic failure",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No service",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Null PDU",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Radio off",
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(SENT));

        //---when the SMS has been delivered---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS delivered",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(getBaseContext(), "SMS not delivered",
                                Toast.LENGTH_SHORT).show();
                        break;                       
                }
            }
        }, new IntentFilter(DELIVERED));       

        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNo, null, message, sentPI, deliveredPI);

 }     
}

SMS messages are received, the onCreate() method will be invoked. The SMS message is contained and attached to the Intent object (intent - the second parameter in the onReceive() method) via a Bundle object. The messages are stored in an Object array in the PDU format. To extract each message, you use the static createFromPdu() method from the SmsMessage class. The SMS message is then displayed using the Toast class:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import android.widget.Toast;
 
 public class SmsReceiver extends BroadcastReceiver
 {
     @Override
     public void onReceive(Context context, Intent intent)
     {
         //---get the SMS message passed in---
         Bundle bundle = intent.getExtras();       
         SmsMessage[] msgs = null;
         String str = "";           
         if (bundle != null)
         {
             //---retrieve the SMS message received---
             Object[] pdus = (Object[]) bundle.get("pdus");
             msgs = new SmsMessage[pdus.length];           
             for (int i=0; i<msgs.length; i++){
                 msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);               
                 str += "SMS from " + msgs[i].getOriginatingAddress();                    
                 str += " :";
                 str += msgs[i].getMessageBody().toString();
                 str += "\n";       
             }
             //---display the new SMS message---
             Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
         }                        
     }
}

Tuesday, 24 May 2011

Static TableLayout

The TableLayout is built using the TableLayout and the TableRow commands. There is no TableCols like the <td> tag in HTML. To align your view in columns you have to set the width of the elements and manually control the layout.
<TableLayout android:id="@+id/TableLayout01" android:layout_width="fill_parent" android:layout_height="wrap_content"  android:stretchColumns="0">

  <TableRow android:id="@+id/TableRow01" android:layout_width="wrap_content" android:layout_height="wrap_content">
    <TextView android:id="@+id/TextView01" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="textfield 1-1"></TextView>

    <CheckBox android:id="@+id/CheckBox01" android:layout_width="wrap_content" android:layout_height="wrap_content"></CheckBox>
  </TableRow>

  <TableRow android:id="@+id/TableRow02" android:layout_width="wrap_content" android:layout_height="wrap_content">
    <TextView android:id="@+id/TextView03" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="textfield 2-1"></TextView>
    <TextView android:id="@+id/TextView04" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="textfield 2-2"></TextView>
  </TableRow>

</TableLayout>
<TableLayout android:id="@+id/tableLayout1" android:layout_height="wrap_content" android:layout_width="match_parent">
    <TableRow android:id="@+id/tableRow1" android:layout_width="wrap_content" android:layout_height="wrap_content">
        <Button android:text="Button" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
        <RadioButton android:text="RadioButton" android:id="@+id/radioButton1" android:layout_width="wrap_content" android:layout_height="wrap_content"></RadioButton>
        <ProgressBar android:layout_height="wrap_content" android:id="@+id/progressBar1" android:layout_width="wrap_content"></ProgressBar>
    </TableRow>
</TableLayout>
<TableLayout android:id="@+id/tableLayout2" android:layout_height="wrap_content" android:layout_width="match_parent">
    <TableRow android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/tableRow2">
        <SeekBar android:layout_height="wrap_content" android:id="@+id/seekBar1" android:layout_width="fill_parent"></SeekBar>
        <DigitalClock android:text="DigitalClock" android:id="@+id/digitalClock1" android:layout_width="wrap_content" android:layout_height="wrap_content"></DigitalClock>
        <ZoomButton android:src="@android:drawable/btn_plus" android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/zoomButton1"></ZoomButton>
        <ToggleButton android:text="ToggleButton" android:id="@+id/toggleButton1" android:layout_width="wrap_content" android:layout_height="wrap_content"></ToggleButton>
    </TableRow>
</TableLayout>
<TableLayout android:id="@+id/tableLayout3" android:layout_height="wrap_content" android:layout_width="match_parent" android:stretchColumns="0">
    <TableRow android:id="@+id/tableRow3" android:layout_width="wrap_content" android:layout_height="wrap_content">
        <SeekBar android:layout_height="wrap_content" android:id="@+id/seekBar2" android:layout_width="fill_parent"></SeekBar>
    </TableRow>
</TableLayout>


How To Add a Row Dynamically

 whenever the button is clicked, it adds a new row to the TableLayout and notice the Scrollbar from the ScrollView.

XML CODE:
<?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/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click To Add New row"></Button>

<ScrollView android:id="@+id/ScrollView01" android:layout_width="wrap_content" android:layout_height="wrap_content">

  <TableLayout android:id="@+id/TableLayout01" android:layout_width="fill_parent" android:layout_height="wrap_content" android:stretchColumns="0">

    <TableRow android:id="@+id/TableRow01" android:layout_width="wrap_content" android:layout_height="wrap_content">
        <TextView android:layout_width="fill_parent" android:text="textfield 1-1" android:layout_height="wrap_content" android:id="@+id/TextView01"></TextView>
        <ImageView android:id="@+id/imageView1" android:layout_height="wrap_content" android:src="@drawable/icon" android:layout_width="wrap_content"></ImageView>
      <DigitalClock android:text="DigitalClock" android:layout_width="wrap_content" android:id="@+id/digitalClock1" android:layout_height="wrap_content"></DigitalClock>
      <CheckBox android:id="@+id/CheckBox01" android:text="" android:layout_width="wrap_content" android:layout_height="wrap_content"></CheckBox>
    </TableRow>

  </TableLayout>
</ScrollView>
</LinearLayout>

Tuesday, 17 May 2011

How to use calendar in android


In this apps we use four class to run calendarview.
first class name as CalendarActivity,Cell,TestActivity,calendarView.Before that we download a images like background.png,calendar_week.png,typeb_calendar_today.png. insert into Drawable folder,because to show and set a day in calendar format .





 






package com.exina.android.calendar;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class CalendarActivity extends Activity  implements CalendarView.OnCellTouchListener{
public static final String MIME_TYPE = "vnd.android.cursor.dir/vnd.exina.android.calendar.date";
CalendarView mView = null;
TextView mHit;
Handler mHandler = new Handler();
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mView = (CalendarView)findViewById(R.id.calendar);
        mView.setOnCellTouchListener(this);
        
        if(getIntent().getAction().equals(Intent.ACTION_PICK))
        findViewById(R.id.hit).setVisibility(View.INVISIBLE);
    }

public void onTouch(Cell cell) {
Intent intent = getIntent();
String action = intent.getAction();
if(action.equals(Intent.ACTION_PICK) || action.equals(Intent.ACTION_GET_CONTENT)) {
Intent ret = new Intent();
ret.putExtra("year", mView.getYear());
ret.putExtra("month", mView.getMonth());
ret.putExtra("day", cell.getDayOfMonth());
this.setResult(RESULT_OK, ret);
finish();
return;
}
int day = cell.getDayOfMonth();
if(mView.firstDay(day))
mView.previousMonth();
else if(mView.lastDay(day))
mView.nextMonth();
else
return;

mHandler.post(new Runnable() {
public void run() {
Toast.makeText(CalendarActivity.this, DateUtils.getMonthString(mView.getMonth(), DateUtils.LENGTH_LONG) + " "+mView.getYear(), Toast.LENGTH_SHORT).show();
}
});
}

    
}



import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.util.Log;

public class Cell {
private static final String TAG = "Cell";
protected Rect mBound = null;
protected int mDayOfMonth = 1; // from 1 to 31
protected Paint mPaint = new Paint(Paint.SUBPIXEL_TEXT_FLAG
            |Paint.ANTI_ALIAS_FLAG);
int dx, dy;
public Cell(int dayOfMon, Rect rect, float textSize, boolean bold) {
mDayOfMonth = dayOfMon;
mBound = rect;
mPaint.setTextSize(textSize/*26f*/);
mPaint.setColor(Color.BLACK);
if(bold) mPaint.setFakeBoldText(true);
dx = (int) mPaint.measureText(String.valueOf(mDayOfMonth)) / 2;
dy = (int) (-mPaint.ascent() + mPaint.descent()) / 2;
}
public Cell(int dayOfMon, Rect rect, float textSize) {
this(dayOfMon, rect, textSize, false);
}
protected void draw(Canvas canvas) {
canvas.drawText(String.valueOf(mDayOfMonth), mBound.centerX() - dx, mBound.centerY() + dy, mPaint);
}
public int getDayOfMonth() {
return mDayOfMonth;
}
public boolean hitTest(int x, int y) {
return mBound.contains(x, y); 
}
public Rect getBound() {
return mBound;
}
public String toString() {
return String.valueOf(mDayOfMonth)+"("+mBound.toString()+")";
}
}




import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.widget.Toast;

public class TestActivity extends PreferenceActivity implements Preference.OnPreferenceClickListener{
@Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
addPreferencesFromResource(R.xml.test);
findPreference("show").setIntent(new Intent(Intent.ACTION_VIEW).setDataAndType(null, CalendarActivity.MIME_TYPE));
findPreference("pick").setOnPreferenceClickListener(this);
findPreference("about").setOnPreferenceClickListener(this);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode==RESULT_OK) {
int year = data.getIntExtra("year", 0);
int month = data.getIntExtra("month", 0);
int day = data.getIntExtra("day", 0);
final Calendar dat = Calendar.getInstance();
dat.set(Calendar.YEAR, year);
dat.set(Calendar.MONTH, month);
dat.set(Calendar.DAY_OF_MONTH, day);
SimpleDateFormat format = new SimpleDateFormat("yyyy MMM dd");
Toast.makeText(TestActivity.this, format.format(dat.getTime()), Toast.LENGTH_LONG).show();
}
}
public boolean onPreferenceClick(Preference  preference) {
String key = preference.getKey();
if(key.equals("pick")) {
startActivityForResult(new Intent(Intent.ACTION_PICK).setDataAndType(null, CalendarActivity.MIME_TYPE), 100);
} else if(key.equals("about")) {
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle(R.string.app_name).setMessage("http://saga-androidapplication.webgarden.com/\n\nBy Saga<arun.saga@yahoo.in>").create().show();
}
return true;
}
}

import java.util.Calendar;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.MonthDisplayHelper;
import android.view.MotionEvent;
import android.widget.ImageView;

public class CalendarView extends ImageView {
    private static int WEEK_TOP_MARGIN = 74;
    private static int WEEK_LEFT_MARGIN = 40;
    private static int CELL_WIDTH = 58;
    private static int CELL_HEIGH = 53;
    private static int CELL_MARGIN_TOP = 92;
    private static int CELL_MARGIN_LEFT = 39;
    private static float CELL_TEXT_SIZE;
    
private static final String TAG = "CalendarView"; 
private Calendar mRightNow = null;
    private Drawable mWeekTitle = null;
    private Cell mToday = null;
    private Cell[][] mCells = new Cell[6][7];
    private OnCellTouchListener mOnCellTouchListener = null;
    MonthDisplayHelper mHelper;
    Drawable mDecoration = null;
    
public interface OnCellTouchListener {
    public void onTouch(Cell cell);
    }

public CalendarView(Context context) {
this(context, null);
}
public CalendarView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}

public CalendarView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mDecoration = context.getResources().getDrawable(R.drawable.typeb_calendar_today);
initCalendarView();
}
private void initCalendarView() {
mRightNow = Calendar.getInstance();
// prepare static vars
Resources res = getResources();
WEEK_TOP_MARGIN  = (int) res.getDimension(R.dimen.week_top_margin);
WEEK_LEFT_MARGIN = (int) res.getDimension(R.dimen.week_left_margin);
CELL_WIDTH = (int) res.getDimension(R.dimen.cell_width);
CELL_HEIGH = (int) res.getDimension(R.dimen.cell_heigh);
CELL_MARGIN_TOP = (int) res.getDimension(R.dimen.cell_margin_top);
CELL_MARGIN_LEFT = (int) res.getDimension(R.dimen.cell_margin_left);
CELL_TEXT_SIZE = res.getDimension(R.dimen.cell_text_size);
// set background
setImageResource(R.drawable.background);
mWeekTitle = res.getDrawable(R.drawable.calendar_week);
mWeekTitle.setBounds(WEEK_LEFT_MARGIN, WEEK_TOP_MARGIN, WEEK_LEFT_MARGIN+mWeekTitle.getMinimumWidth(), WEEK_TOP_MARGIN+mWeekTitle.getMinimumHeight());
mHelper = new MonthDisplayHelper(mRightNow.get(Calendar.YEAR), mRightNow.get(Calendar.MONTH));
initCells();
    }
private void initCells() {
   class _calendar {
    public int day;
    public boolean thisMonth;
    public _calendar(int d, boolean b) {
    day = d;
    thisMonth = b;
    }
    public _calendar(int d) {
    this(d, false);
    }
   };
   _calendar tmp[][] = new _calendar[6][7];
   
   for(int i=0; i<tmp.length; i++) {
    int n[] = mHelper.getDigitsForRow(i);
    for(int d=0; d<n.length; d++) {
    if(mHelper.isWithinCurrentMonth(i,d))
    tmp[i][d] = new _calendar(n[d], true);
    else
    tmp[i][d] = new _calendar(n[d]);
   
    }
   }

   Calendar today = Calendar.getInstance();
   int thisDay = 0;
   mToday = null;
   if(mHelper.getYear()==today.get(Calendar.YEAR) && mHelper.getMonth()==today.get(Calendar.MONTH)) {
    thisDay = today.get(Calendar.DAY_OF_MONTH);
   }
// build cells
Rect Bound = new Rect(CELL_MARGIN_LEFT, CELL_MARGIN_TOP, CELL_WIDTH+CELL_MARGIN_LEFT, CELL_HEIGH+CELL_MARGIN_TOP);
for(int week=0; week<mCells.length; week++) {
for(int day=0; day<mCells[week].length; day++) {
if(tmp[week][day].thisMonth) {
if(day==0 || day==6 )
mCells[week][day] = new RedCell(tmp[week][day].day, new Rect(Bound), CELL_TEXT_SIZE);
else 
mCells[week][day] = new Cell(tmp[week][day].day, new Rect(Bound), CELL_TEXT_SIZE);
} else
mCells[week][day] = new GrayCell(tmp[week][day].day, new Rect(Bound), CELL_TEXT_SIZE);
Bound.offset(CELL_WIDTH, 0); // move to next column 
// get today
if(tmp[week][day].day==thisDay) {
mToday = mCells[week][day];
mDecoration.setBounds(mToday.getBound());
}
}
Bound.offset(0, CELL_HEIGH); // move to next row and first column
Bound.left = CELL_MARGIN_LEFT;
Bound.right = CELL_MARGIN_LEFT+CELL_WIDTH;
}
}

    public void setTimeInMillis(long milliseconds) {
    mRightNow.setTimeInMillis(milliseconds);
    initCells();
    this.invalidate();
    }
        
    public int getYear() {
    return mHelper.getYear();
    }
    
    public int getMonth() {
    return mHelper.getMonth();
    }
    
    public void nextMonth() {
    mHelper.nextMonth();
    initCells();
    invalidate();
    }
    
    public void previousMonth() {
    mHelper.previousMonth();
    initCells();
    invalidate();
    }
    
    public boolean firstDay(int day) {
    return day==1;
    }
    
    public boolean lastDay(int day) {
    return mHelper.getNumberOfDaysInMonth()==day;
    }
    
    public void goToday() {
    Calendar cal = Calendar.getInstance();
    mHelper = new MonthDisplayHelper(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH));
    initCells();
    invalidate();
    }
    
    public Calendar getDate() {
    return mRightNow;
    }
    
    @Override
    public boolean onTouchEvent(MotionEvent event) {
    if(mOnCellTouchListener!=null){
    for(Cell[] week : mCells) {
for(Cell day : week) {
if(day.hitTest((int)event.getX(), (int)event.getY())) {
mOnCellTouchListener.onTouch(day);
}
}
}
    }
    return super.onTouchEvent(event);
    }
  
    public void setOnCellTouchListener(OnCellTouchListener p) {
mOnCellTouchListener = p;
}

@Override
protected void onDraw(Canvas canvas) {
// draw background
super.onDraw(canvas);
mWeekTitle.draw(canvas);
// draw cells
for(Cell[] week : mCells) {
for(Cell day : week) {
day.draw(canvas);
}
}
// draw today
if(mDecoration!=null && mToday!=null) {
mDecoration.draw(canvas);
}
}
private class GrayCell extends Cell {
public GrayCell(int dayOfMon, Rect rect, float s) {
super(dayOfMon, rect, s);
mPaint.setColor(Color.LTGRAY);
}
}
private class RedCell extends Cell {
public RedCell(int dayOfMon, Rect rect, float s) {
super(dayOfMon, rect, s);
mPaint.setColor(0xdddd0000);
}
}

}
xml file name as 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"
    >
<com.exina.android.calendar.CalendarView  android:id="@+id/calendar"
   android:layout_width="fill_parent" 
   android:layout_height="wrap_content" />
    <TextView android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/app_name" />
    <TextView android:id="@+id/hit"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hit" />
   
</LinearLayout>



Go to AndroidManifest.xml .

package="com.exina.android.calendar"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".CalendarActivity"
                  android:label="@string/app_name">
            
            <intent-filter>
                <action android:name="android.intent.action.PICK" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="vnd.android.cursor.dir/vnd.exina.android.calendar.date" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="vnd.android.cursor.dir/vnd.exina.android.calendar.date" />
            </intent-filter>
        </activity>

    <activity android:label="@string/app_name"
     android:name=".TestActivity" android:icon="@drawable/icon">
    <intent-filter>
    <action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>



Output: