<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>www.vimviv.com</title>
	
	<link>http://blog.vimviv.com</link>
	<description>www.vimviv.com is an effort to provide you everything related to your mobile at a single place. Here you can search, upload and download things for your mobile. Technical articles are available for mobile application developers.</description>
	<lastBuildDate>Mon, 13 May 2013 12:24:29 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/vimviv" /><feedburner:info uri="vimviv" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Android SQLite Database</title>
		<link>http://feedproxy.google.com/~r/vimviv/~3/Sq0HcXb2Kik/</link>
		<comments>http://blog.vimviv.com/android/android-sqlite-database/#comments</comments>
		<pubDate>Sun, 12 May 2013 09:08:03 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[sqlite]]></category>

		<guid isPermaLink="false">http://blog.vimviv.com/?p=628</guid>
		<description><![CDATA[In this post we will discuss how to store data in the android sqlite database. Android is using light weight open source sqlite database as one of the way to store data. Android provides two important classes SQLiteDatabase class to perform common database management tasks e.g. create, delete, execute SQL commands,etc and a helper class [...]<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href='http://blog.vimviv.com/android/intent-filter-android/' rel='bookmark' title='What is intent filter in android?'>What is intent filter in android?</a></li>
</ol>
<img src='http://yarpp.org/pixels/29e3c972243f67e94906e1c79d9a0b70'/>
</div>
]]></description>
				<content:encoded><![CDATA[<p>In this post we will discuss how to store data in the android sqlite database. Android is using light weight open source sqlite database as one of the way to store data. Android provides two important classes SQLiteDatabase class to perform common database management tasks e.g. create, delete, execute SQL commands,etc and a helper class SQLiteOpenHelper to manage database creation and version management.</p>
<p><span id="more-628"></span><br />
1. So first we will create a database helper class by extending SQLiteOpenHelper.<br />
a. In the constructor we need to pass database name and version number. In this example i am creating the DatabaseHelper class as singleton class. So we can get instance of DatabaseHelper using static method getInstance.</p>
<pre name="code" class="java">

  synchronized static DatabaseHelper getInstance(Context context) {
        if (singleton == null) {
            singleton = new DatabaseHelper(context.getApplicationContext());
        }
        return (singleton);
    }

    private DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, SCHEMA_VERSION);
    }
</pre>
<p>b. For contact table column we are implementing BaseColumns interface. BaseColumns interface providers _id and _count column for us.</p>
<pre name="code" class="java">

    public static final class ContactColumns implements BaseColumns {

        public static final String NAME = "name";

        public static final String PHONE_NUMBER = "phoneNumber";

        public static final String EMAIL = "email";

        public static final String ADDRESS = "address";
    }
</pre>
<p>c. override the onCreate method of SQLiteOpenHelper. onCreate method will be called when the database is created first time. In this method we will get the instance of  SQLiteDatabase. We are using execSQL method of SQLiteDatabase for creating table. execSQL method doesn’t return anything so it should not be used for sql statement that return data.</p>
<pre name="code" class="java">

    @Override
    public void onCreate(SQLiteDatabase db) {
        String s = " (" +
                ContactColumns._ID + " INTEGER PRIMARY KEY, " +
                ContactColumns.NAME + " TEXT, " +
                ContactColumns.PHONE_NUMBER + " TEXT, " +
                ContactColumns.EMAIL + " TEXT, " +
                ContactColumns.ADDRESS + " TEXT" +
                ");";

        db.execSQL("CREATE TABLE " + TABLE_NAME + s);

    }

</pre>
<p>d. onUpgrade is the second method that we need to override. onUpgrade is called when database needs to be upgraded. Suppose address column was not there in version 1 of contact’s table.This column is added in version 2. In that case when you try to reinstall app with version 2 database onUpgrade method will be called. In onUpgrade method, we will check if old version is 1 , alter the table and add column address. for other versions just drop the table and create again.</p>
<pre name="code" class="java">

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        // Logs that the database is being upgraded
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");

        // if (oldVersion == 1) {
        // try {
        // db.execSQL("alter table " + TABLE_NAME
        // + " add column " + "address" +
        // " TEXT;");
        // } catch (SQLException e) {
        // // Shouldn't be needed unless we're debugging and interrupt the
        // // process
        // Log.w(TAG, "Exception upgrading EmailProvider.db from 19 to 20 " +
        // e);
        // }
        // } else {
        // // Drop older table if existed
        // db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        //
        // // Create tables again
        // onCreate(db);
        // }
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);

        // Create tables again
        onCreate(db);

    }

}
</pre>
<p>2. create ContactData data only class. it will hold all contact information as single entity. We are making ContactData class Serializable because we can send ContactsData object from one activty to another or we can save state of activity with ContactsData object.</p>
<pre name="code" class="java">

public class ContactsData implements Serializable{

    public int mId;
    public String mName;
    public String mPhoneNumber;
    public String mAddress;
    public String mEmail;

    public ContactsData(int id, String name, String phoneNumber) {
        this(id,name,phoneNumber,null,null);
    }
    
    public ContactsData(int id, String name, String phoneNumber,String address, String email) {
        mId = id;
        mName = name;
        mPhoneNumber = phoneNumber;
        mAddress = address;
        mEmail = email;
    }
    
    public ContactsData() {}


}

</pre>
<p>3. Now we will write methods for database read write operations.</p>
<pre name="code" class="java">

 mDatabaseHelper = DatabaseHelper.getInstance(context);
</pre>
<p><strong>Add new contact:</strong></p>
<p>a. get writable databse.<br />
b. store column name and value in ContentValues as key value pair<br />
c. use insert method for inserting contacts data with arguments.<br />
d. if values are empty, ContactColumns.NAME(nullColumnHack) column can be null.<br />
e. insert method returns rowId of inserted row.</p>
<pre name="code" class="java">

  // Adding new contact
    public void addContact(ContactsData contact){
        SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(ContactColumns.NAME, contact.mName); // Contact Name
        values.put(ContactColumns.PHONE_NUMBER, contact.mPhoneNumber); // Contact phone number
        values.put(ContactColumns.EMAIL, contact.mEmail); // Contact email
        values.put(ContactColumns.ADDRESS, contact.mAddress); // Contact address 
        // Inserting Row
        long rowId = db.insert(DatabaseHelper.TABLE_NAME, ContactColumns.NAME, values);
        db.close();
    }
</pre>
<p><strong>Getting single contact:</strong></p>
<p>a. get readable database.<br />
b. we will use query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)<br />
c. query method will return resultset as cursor.</p>
<pre name="code" class="java">

// Getting single contact
    public ContactsData getContact(int id) {
        SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();

              Cursor cursor = db.query(
                /* FROM */ DatabaseHelper.TABLE_NAME, 
                /* SELECT */ new String[] {ContactColumns._ID,ContactColumns.NAME, ContactColumns.PHONE_NUMBER}, 
                /* WHERE */ ContactColumns._ID + "=?",
                /* WHERE args */new String[] {String.valueOf(id)}, 
                /* GROUP BY */null, 
                /* HAVING */null, 
                /* ORDER BY */ ContactColumns.NAME+" DESC", 
                /* LIMIT */null);

        if (cursor != null)
            cursor.moveToFirst();
        ContactsData contact = new ContactsData(Integer.parseInt(
                cursor.getString(cursor.getColumnIndex(ContactColumns._ID))),
                cursor.getString(cursor.getColumnIndex(ContactColumns.NAME)),
                cursor.getString(cursor.getColumnIndex(ContactColumns.PHONE_NUMBER)));
        return contact;
    }
</pre>
<p><strong>Get all contacts:</strong></p>
<pre name="code" class="java">

// Getting All Contacts
    public List<ContactsData> getAllContacts() {
        List<ContactsData> contactList = new ArrayList<ContactsData>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + DatabaseHelper.TABLE_NAME;

        SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        while (cursor.moveToNext()) {
            ContactsData contact = new ContactsData(Integer.parseInt(
                    cursor.getString(cursor.getColumnIndex(ContactColumns._ID))),
                    cursor.getString(cursor.getColumnIndex(ContactColumns.NAME)),
                    cursor.getString(cursor.getColumnIndex(ContactColumns.PHONE_NUMBER)));
            // Adding contact to list
            contactList.add(contact);

        }
        // return contact list
        return contactList;
    }
</pre>
<p><strong>Update single contact:</strong></p>
<pre name="code" class="java">

 // Updating single contact
    public int updateContact(ContactsData contact) {
        SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(ContactColumns.NAME, contact.mName);
        values.put(ContactColumns.PHONE_NUMBER, contact.mPhoneNumber);

        // updating row
        return db.update(DatabaseHelper.TABLE_NAME, values, ContactColumns._ID + " = ?",
                new String[] {
                    String.valueOf(contact.mId)
                });
    }
</pre>
<p><strong>Delete single contact:</strong></p>
<pre name="code" class="java">

    // Deleting single contact
    public void deleteContact(ContactsData contact) {
        SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
        db.delete(DatabaseHelper.TABLE_NAME, ContactColumns._ID + " = ?",
                new String[] {
                    String.valueOf(contact.mId)
                });
        db.close();
    }

</pre>
<p><strong>contact count:</strong></p>
<pre name="code" class="java">

 // Getting contacts Count
    public int getContactsCount() {
        String countQuery = "SELECT  * FROM " + DatabaseHelper.TABLE_NAME;
        SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        // return count
        return cursor.getCount();
    }
</pre>
<h4>Incoming search terms:</h4><ul><li><a href="http://blog.vimviv.com/android/android-sqlite-database/" title="android singleton database helper">android singleton database helper</a> (2)</li><li><a href="http://blog.vimviv.com/android/android-sqlite-database/" title="how to delete data from a database in android">how to delete data from a database in android</a> (2)</li><li><a href="http://blog.vimviv.com/android/android-sqlite-database/" title="android sms database">android sms database</a> (1)</li></ul><div class='yarpp-related-rss'>
<p>Related posts:</p><ol>
<li><a href='http://blog.vimviv.com/android/intent-filter-android/' rel='bookmark' title='What is intent filter in android?'>What is intent filter in android?</a></li>
</ol>
<img src='http://yarpp.org/pixels/29e3c972243f67e94906e1c79d9a0b70'/>
</div>
<img src="http://feeds.feedburner.com/~r/vimviv/~4/Sq0HcXb2Kik" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.vimviv.com/android/android-sqlite-database/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.vimviv.com/android/android-sqlite-database/</feedburner:origLink></item>
		<item>
		<title>Android Date Picker DialogFragment</title>
		<link>http://feedproxy.google.com/~r/vimviv/~3/wmAhfFB89FA/</link>
		<comments>http://blog.vimviv.com/android/android-date-picker-dialogfragment/#comments</comments>
		<pubDate>Mon, 06 May 2013 15:44:43 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
				<category><![CDATA[Android]]></category>

		<guid isPermaLink="false">http://blog.vimviv.com/?p=617</guid>
		<description><![CDATA[In this post we will discuss about creating datepicker using DialogFragment. Google recommends that we use DialogFragment instead of simple dialog with Activity.showDialog. DialogFragment will automatically manage life cycle for us. 1. Create class for date picker dialog fragment a. define a public default constructor otherwise it will crash on screen rotation. b. Define the [...]<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href='http://blog.vimviv.com/android/intent-filter-android/' rel='bookmark' title='What is intent filter in android?'>What is intent filter in android?</a></li>
</ol>
<img src='http://yarpp.org/pixels/29e3c972243f67e94906e1c79d9a0b70'/>
</div>
]]></description>
				<content:encoded><![CDATA[<p>In this post we will discuss about creating datepicker using DialogFragment. Google recommends that we use DialogFragment instead of simple dialog with Activity.showDialog. DialogFragment will automatically manage life cycle for us.</p>
<p><strong>1.</strong> Create class for date picker dialog fragment</p>
<p>a. define a public default constructor otherwise it will crash on screen rotation.<br />
b. Define the onCreateDialog() method to return an instance of DatePickerDialog<br />
c. pass OnDateSetListener to the constructor of DatePickerDialog.<br />
<span id="more-617"></span></p>
<pre name="code" class="java">

public class DatePickerDialogFragment extends DialogFragment {

    private DatePickerDialog.OnDateSetListener mDateSetListener;

    public DatePickerDialogFragment() {

    }

    DatePickerDialogFragment(OnDateSetListener dateSetListener) {
        mDateSetListener = dateSetListener;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        DatePickerDialog dpd = new DatePickerDialog(getActivity(), mDateSetListener, year, month,
                day);
        // dpd.getDatePicker().setCalendarViewShown(true);
        // dpd.getDatePicker().setSpinnersShown(false);

        return dpd;
    }

}
</pre>
<p><strong>2.</strong> For activating date picker and for displaying selected date we will use button that will look more like spinner with the help of spinner style.</p>
<pre name="code" class="xml">

    <Button
        android:id="@+id/select_date"
        style="@android:style/Widget.DeviceDefault.Light.Spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
    </Button>
</pre>
<div id="attachment_618" class="wp-caption aligncenter" style="width: 310px"><a href="http://i2.wp.com/blog.vimviv.com/wp-content/uploads/2013/05/spinner_style.png"><img class="size-medium wp-image-618" alt="spinner style button" src="http://i2.wp.com/blog.vimviv.com/wp-content/uploads/2013/05/spinner_style.png?resize=300%2C41" data-recalc-dims="1" /></a><p class="wp-caption-text">spinner style button</p></div>
<p><strong>3.</strong> use current date as default label of button</p>
<pre name="code" class="java">
  selectDate = (Button) findViewById(R.id.select_date);
  setDate(System.currentTimeMillis());
</pre>
<p><strong>4.</strong> show date picker on click of select_date button.</p>
<pre name="code" class="java">

selectDate.setOnClickListener(datePickerListener);
 OnClickListener datePickerListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            DialogFragment newFragment = new DatePickerDialogFragment(callback);
        newFragment.show(getSupportFragmentManager(), "datePicker");

        }
    };
</pre>
<div id="attachment_619" class="wp-caption aligncenter" style="width: 310px"><a href="http://i0.wp.com/blog.vimviv.com/wp-content/uploads/2013/05/Screen-Shot-2013-05-06-at-1.50.20-PM.png"><img src="http://i0.wp.com/blog.vimviv.com/wp-content/uploads/2013/05/Screen-Shot-2013-05-06-at-1.50.20-PM.png?resize=300%2C279" alt="date picker" class="size-medium wp-image-619" data-recalc-dims="1" /></a><p class="wp-caption-text">date picker</p></div>
<p><strong>5.</strong> Define the callback of DatePickerDialogFragment</p>
<pre name="code" class="java">

 OnDateSetListener callback = new OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            Calendar c = Calendar.getInstance();
            c.set(year, monthOfYear, dayOfMonth);
            setDate(c.getTime().getTime());

        }
    };
</pre>
<p><strong>6.</strong> setDate method for date formating.</p>
<pre name="code" class="java">
  private void setDate(long millisecond){
        int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR
                | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_MONTH
                | DateUtils.FORMAT_ABBREV_WEEKDAY;
        String dateString = DateUtils.formatDateTime(EditContactActivity.this,millisecond, flags);
        selectDate.setText(dateString);

    }
</pre>
<p><strong>7.</strong> We can also use CalendarView for date picker.</p>
<pre name="code" class="java">
        DatePickerDialog dpd = new DatePickerDialog(getActivity(), mDateSetListener, year, month,
                day);
        dpd.getDatePicker().setCalendarViewShown(true);
        dpd.getDatePicker().setSpinnersShown(false);
</pre>
<div id="attachment_625" class="wp-caption aligncenter" style="width: 310px"><a href="http://i2.wp.com/blog.vimviv.com/wp-content/uploads/2013/05/Screen-Shot-2013-05-06-at-1.45.12-PM.png"><img src="http://i2.wp.com/blog.vimviv.com/wp-content/uploads/2013/05/Screen-Shot-2013-05-06-at-1.45.12-PM.png?resize=300%2C279" alt="Calendar view picker" class="size-medium wp-image-625" data-recalc-dims="1" /></a><p class="wp-caption-text">Calendar view picker</p></div>
<h4>Incoming search terms:</h4><ul><li><a href="http://blog.vimviv.com/android/android-date-picker-dialogfragment/" title="android CalendarView setDate">android CalendarView setDate</a> (9)</li><li><a href="http://blog.vimviv.com/android/android-date-picker-dialogfragment/" title="android datepicker only year">android datepicker only year</a> (1)</li><li><a href="http://blog.vimviv.com/android/android-date-picker-dialogfragment/" title="dialogfragment">dialogfragment</a> (1)</li></ul><div class='yarpp-related-rss'>
<p>Related posts:</p><ol>
<li><a href='http://blog.vimviv.com/android/intent-filter-android/' rel='bookmark' title='What is intent filter in android?'>What is intent filter in android?</a></li>
</ol>
<img src='http://yarpp.org/pixels/29e3c972243f67e94906e1c79d9a0b70'/>
</div>
<img src="http://feeds.feedburner.com/~r/vimviv/~4/wmAhfFB89FA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.vimviv.com/android/android-date-picker-dialogfragment/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.vimviv.com/android/android-date-picker-dialogfragment/</feedburner:origLink></item>
		<item>
		<title>Android custom save and discard type ActionBar</title>
		<link>http://feedproxy.google.com/~r/vimviv/~3/xs3XQsO0N8w/</link>
		<comments>http://blog.vimviv.com/android/custom-save-discard-actionbar/#comments</comments>
		<pubDate>Thu, 02 May 2013 05:49:35 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
				<category><![CDATA[Android]]></category>

		<guid isPermaLink="false">http://blog.vimviv.com/?p=610</guid>
		<description><![CDATA[Before android 3.0, users used to press hardware menu button, to see what all actions are available for current screen. As of android 3.0, the hardware menu button is not available on android devices and options menu is replaced by action bar. Actionbar is a bar on top of the activity. It can provide actions [...]<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href='http://blog.vimviv.com/android/started-android/' rel='bookmark' title='Getting Started With Android'>Getting Started With Android</a></li>
<li><a href='http://blog.vimviv.com/android/intent-android/' rel='bookmark' title='What is Intent in android?'>What is Intent in android?</a></li>
<li><a href='http://blog.vimviv.com/android/intent-filter-android/' rel='bookmark' title='What is intent filter in android?'>What is intent filter in android?</a></li>
</ol>
<img src='http://yarpp.org/pixels/29e3c972243f67e94906e1c79d9a0b70'/>
</div>
]]></description>
				<content:encoded><![CDATA[<p>Before android 3.0, users used to press hardware menu button, to see what all actions are available for current screen.<br />
As of android 3.0, the hardware menu button is not available on android devices and options menu is replaced by action bar.<br />
Actionbar is a bar on top of the activity. It can provide actions and navigation using views.</p>
<p>We can add custom views to actionbar using setCustomView method that takes View as argument. for that first we need to enable DISPLAY_SHOW_CUSTOM option.<br />
In this article we will see how we can create custom actionbar (save and discard actionbar).<br />
<span id="more-610"></span><br />
1. first we will create custom_actionbar.xml file</p>
<pre name="code" class="xml">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:divider="?android:attr/dividerVertical"
    android:dividerPadding="12dip"
    android:orientation="horizontal"
    android:showDividers="middle" >

    <!-- id must match corresponding menu item id -->

    <LinearLayout
        android:id="@+id/action_cancel"
        style="@style/CustomActionButton" >

        <ImageView
            style="@style/CustomActionButtonImage"
            android:src="@android:drawable/ic_menu_close_clear_cancel" />

        <TextView
            style="@style/CustomActionButtonText"
            android:text="Discard" />
    </LinearLayout>

    <!-- id must match corresponding menu item id -->

    <LinearLayout
        android:id="@+id/action_done"
        style="@style/CustomActionButton" >

        <ImageView
            style="@style/CustomActionButtonImage"
            android:src="@android:drawable/ic_menu_save" />

        <TextView
            style="@style/CustomActionButtonText"
            android:text="Save"
            />
    </LinearLayout>

</LinearLayout>

</pre>
<p>2. in this layout we have defined common properties in custom styles. </p>
<pre name="code" class="xml">

     <style name="CustomActionButton" parent="android:style/Widget.Holo.Light.ActionButton">
        <item name="android:layout_height">match_parent</item>
        <item name="android:layout_width">0dp</item>
        <item name="android:layout_weight">1</item>
        <item name="android:focusable">true</item>
        <item name="android:orientation">horizontal</item>
    </style>
    <style name="CustomActionButtonImage">
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_width">wrap_content</item>
        <item name="android:padding">4dp</item>
    </style>
    <style name="CustomActionButtonText">
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_width">wrap_content</item>
        <item name="android:textAppearance">?android:attr/actionMenuTextAppearance</item>
        <item name="android:textColor">?android:attr/actionMenuTextColor</item>
        <item name="android:orientation">horizontal</item>
        <item name="android:singleLine">true</item>
        <item name="android:ellipsize">none</item>
        <item name="android:padding">4dp</item>
    </style>

</pre>
<p>3. Now in our activity we will inflate this layout and add to actionbar.</p>
<pre name="code" class="java">

  LayoutInflater inflater = LayoutInflater.from(this);

        View actionBarButtons = inflater.inflate(R.layout.custom_actionbar, new LinearLayout(this),
                false);

        View cancelActionView = actionBarButtons.findViewById(R.id.action_cancel);
        cancelActionView.setOnClickListener(mActionBarListener);
        View doneActionView = actionBarButtons.findViewById(R.id.action_done);
        doneActionView.setOnClickListener(mActionBarListener);

        getActionBar().setCustomView(actionBarButtons);
        getActionBar().setDisplayOptions(
                ActionBar.DISPLAY_SHOW_CUSTOM,
                ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME
                        | ActionBar.DISPLAY_SHOW_TITLE
                        | ActionBar.DISPLAY_SHOW_CUSTOM);

</pre>
<p>a. inflate takes xml layout and gives us java object.<br />
b. using setDisplayOptions, we can set multiple display options. like in this example.<br />
we don’t want home as up, home and title, we only want  DISPLAY_SHOW_CUSTOM.</p>
<p>4. handle click event of buttons.</p>
<pre name="code" class="java">

  private final View.OnClickListener mActionBarListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.action_done:
                    onSave();
                    break;

                case R.id.action_cancel:
                    finish();
                    break;
            }
        }

    };
</pre>
<p>5. declare activity in AndroidManifest.xml file</p>
<pre name="code" class="java">

<activity
            android:name=".MainActivity"
            android:label="@string/app_name" android:theme="@android:style/Theme.Holo.Light">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
</pre>
<p>And here is the screen shot<br />
<div id="attachment_611" class="wp-caption aligncenter" style="width: 310px"><a href="http://i0.wp.com/blog.vimviv.com/wp-content/uploads/2013/05/CustomActionBar.png"><img src="http://i0.wp.com/blog.vimviv.com/wp-content/uploads/2013/05/CustomActionBar.png?resize=300%2C45" alt="Custom Actionbar" class="size-medium wp-image-611" data-recalc-dims="1" /></a><p class="wp-caption-text">Custom Actionbar</p></div></p>
<div class='yarpp-related-rss'>
<p>Related posts:</p><ol>
<li><a href='http://blog.vimviv.com/android/started-android/' rel='bookmark' title='Getting Started With Android'>Getting Started With Android</a></li>
<li><a href='http://blog.vimviv.com/android/intent-android/' rel='bookmark' title='What is Intent in android?'>What is Intent in android?</a></li>
<li><a href='http://blog.vimviv.com/android/intent-filter-android/' rel='bookmark' title='What is intent filter in android?'>What is intent filter in android?</a></li>
</ol>
<img src='http://yarpp.org/pixels/29e3c972243f67e94906e1c79d9a0b70'/>
</div>
<img src="http://feeds.feedburner.com/~r/vimviv/~4/xs3XQsO0N8w" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.vimviv.com/android/custom-save-discard-actionbar/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.vimviv.com/android/custom-save-discard-actionbar/</feedburner:origLink></item>
		<item>
		<title>Creating RESTful web services using jersey</title>
		<link>http://feedproxy.google.com/~r/vimviv/~3/maEud-CYSko/</link>
		<comments>http://blog.vimviv.com/web/creating-restful-web-services-jersey/#comments</comments>
		<pubDate>Sun, 16 Sep 2012 11:37:22 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
				<category><![CDATA[Web]]></category>
		<category><![CDATA[Jersey]]></category>

		<guid isPermaLink="false">http://blog.vimviv.com/?p=564</guid>
		<description><![CDATA[As a mobile developer for end-to-end apps we need to interact with the server. Even if your mobile app is not server client based app, we need some minimum interaction with the server like user authentication, user profile saving on server, etc. So its good to have some idea about development of web services. In [...]<div class='yarpp-related-rss yarpp-related-none'>

No related posts.
<img src='http://yarpp.org/pixels/29e3c972243f67e94906e1c79d9a0b70'/>
</div>
]]></description>
				<content:encoded><![CDATA[<p>As a mobile developer for end-to-end apps we need to interact with the server. Even if your mobile app is not server client based app, we need some minimum interaction with the server like user authentication, user profile saving on server, etc.</p>
<p>So its good to have some idea about development of web services. In this article we will see how easily we can develop RESTful web services using jersey.<br />
<span id="more-564"></span><br />
<strong>Prerequisites:</strong></p>
<p>1.	Eclipse jee(http://www.eclipse.org/downloads/)<br />
2.	Tomcat 7 (http://tomcat.apache.org/download-70.cgi)<br />
3.	Zip of jersey lib (http://jersey.java.net)</p>
<p><strong>Configuration:</strong></p>
<p>1.	Start eclipse and select new -> Dynamic web projects.<br />
<a href="http://i1.wp.com/blog.vimviv.com/wp-content/uploads/2012/09/Screen-Shot-2012-09-16-at-2.44.03-PM.png"><img src="http://i1.wp.com/blog.vimviv.com/wp-content/uploads/2012/09/Screen-Shot-2012-09-16-at-2.44.03-PM.png?resize=230%2C300" alt="new dynamic web project" title="new dynamic web project" class="aligncenter size-medium wp-image-566" data-recalc-dims="1" /></a><br />
2.	Give the name of the project, if target runtime is not defined, give the path of the downloaded tomcat path and click finish.<br />
<a href="http://i2.wp.com/blog.vimviv.com/wp-content/uploads/2012/09/Screen-Shot-2012-09-16-at-3.04.03-PM.png"><img src="http://i2.wp.com/blog.vimviv.com/wp-content/uploads/2012/09/Screen-Shot-2012-09-16-at-3.04.03-PM.png?resize=300%2C187" alt="new project template" title="new project template" class="aligncenter size-medium wp-image-568" data-recalc-dims="1" /></a><br />
3.	Unzip the jersey lib and copy all files to the WebContent ->WEB-INF ->lib.<br />
4.	Create Resources.java file inside src folder.<br />
5.	Now open web.xml file and copy this code.</p>
<p><a href="http://i2.wp.com/blog.vimviv.com/wp-content/uploads/2012/09/Screen-Shot-2012-09-16-at-4.00.12-PM.png"><img src="http://i2.wp.com/blog.vimviv.com/wp-content/uploads/2012/09/Screen-Shot-2012-09-16-at-4.00.12-PM.png?resize=300%2C179" alt="Folder structure" title="Folder structure" class="aligncenter size-medium wp-image-569" data-recalc-dims="1" /></a></p>
<pre name="code" class="xml">
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>contacts</display-name>
  <servlet>
    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>com.sun.jersey.config.property.packages</param-name>
      <param-value>com.vimviv</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app>
</pre>
<p><strong>Annotations:</strong><br />
Jersey is based on the java and it uses annotations for making web services development easy.<br />
So first we will see details of some annotations.</p>
<p>@PATH(your_path): sets the path as your_app_name/servlet name/your_path<br />
@POST: HTTP POST request<br />
@GET: HTTP GET request<br />
@PUT: HTTP PUT request<br />
@DELETE: HTTP DELETE request<br />
@Produces(MediaType.TEXT_PLAIN ): it defines in which mime type method will produce data.<br />
@Consumes(type [, more-types ]): it defines in which mime type method will consume data.<br />
@PathParam: it can extract variable param from url path.<br />
@QueryParam: it can extract query param from url</p>
<p><strong>Start some coding:</strong><br />
<strong>1.	Create new class file contact.java for POJO and add this code.</strong></p>
<pre name="code" class="java">
package com.vimviv;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Contact {

	private int id;
	private String name;
	private String phone;
	
	public Contact() {
		// empty default constructor 
	}
	
	public Contact(int id, String name, String phone){
		this.id = id;
		this.name = name;
		this.phone = phone;
	}
	
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	
}
</pre>
<p><strong>@XmlRootElement:</strong> it will help to convert contact object to json/xml data.<br />
Default constructor: don’t forget to add default constructor otherwise it will give error on runtime.</p>
<p><strong>2.	add simple getinfo() method and run the project.</strong></p>
<pre name="code" class="java">
package com.vimviv;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

@Path("contact")
public class Resources {

	@GET
	@Path("getInfo")
	@Produces(MediaType.TEXT_PLAIN)
	public String getInfo() {
		return "Contact details";
	}
	
}
</pre>
<p>Now we can access getInfo web service with this url </p>
<p>http://localhost:8080/contacts/rest/contact/getInfo</p>
<p>and we will get the output &#8220;Contact details&#8221;;</p>
<p><strong>3.	We can return data in json format</strong></p>
<pre name="code" class="java">
@GET
	@Path("getJsonContact")
	@Produces(MediaType.APPLICATION_JSON)
	public Contact getJsonContact() {
		return new Contact(100,"vimviv","123456789");
	}
</pre>
<p>url: http://localhost:8080/contacts/rest/contact/getJsonContact<br />
output: {&#8220;name&#8221;:&#8221;vimviv&#8221;,&#8221;phone&#8221;:&#8221;123456789&#8243;}</p>
<p>You don’t need to do anything just define media type as MediaType.APPLICATION_JSON  and return contact object.<br />
<strong>4.	We can return data in xml format.</strong></p>
<pre name="code" class="java">
@GET
	@Path("getXmlContact")
	@Produces(MediaType.APPLICATION_XML)
	public Contact getXmlContact() {
		return new Contact(100,"vimviv","123456789");
	}
	
</pre>
<p><strong>url:</strong> http://localhost:8080/contacts/rest/contact/getXmlContact</p>
<p><strong>output:</strong></p>
<pre name="code" class="xml">
<contact>
<name>vimviv</name>
<phone>123456789</phone>
</contact>
</pre>
<p><strong>5.	user can send ID in url path</strong></p>
<pre name="code" class="java">
	@GET
	@Path("{id}")
	@Produces(MediaType.APPLICATION_JSON)
	public Contact getJsonContactPathId(@PathParam("id")String id) {
		int contactId = Integer.parseInt(id);
		Contact contact;
		if(contactId == 100){
			contact= new Contact(contactId,"vimviv","123456789");
		}else{
			contact= new Contact(contactId,"","");
		}
		return contact;
		
	}
</pre>
<p>url: http://localhost:8080/contacts/rest/contact/100<br />
output:<br />
{&#8220;id&#8221;:&#8221;100&#8243;,&#8221;name&#8221;:&#8221;vimviv&#8221;,&#8221;phone&#8221;:&#8221;123456789&#8243;}</p>
<p><strong>6.	User can also send ID as query param.</strong></p>
<pre name="code" class="java">
@GET
	@Path("getContactWithId")
	@Produces(MediaType.APPLICATION_JSON)
	public Contact getJsonContactQueryId(@QueryParam("id")String id) {
		int contactId = Integer.parseInt(id);
		Contact contact;
		if(contactId == 100){
			contact= new Contact(contactId,"vimviv","123456789");
		}else{
			contact= new Contact(contactId,"","");
		}
		return contact;
		
	}
</pre>
<p>url: http://localhost:8080/contacts/rest/contact/getContactWithId?id=100</p>
<p>output:<br />
{&#8220;id&#8221;:&#8221;100&#8243;,&#8221;name&#8221;:&#8221;vimviv&#8221;,&#8221;phone&#8221;:&#8221;123456789&#8243;}</p>
<p><strong>7.	Like GET method we can also use POST method for consuming json data.</strong></p>
<pre name="code" class="java">
	@POST
	@Path("isContactExist")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.TEXT_PLAIN)
	public String isContactExist(Contact contact) {
		boolean isExist = false;
		if(contact.getId()==100 &#038;&#038; "vimviv".equals(contact.getName())&#038;&#038;"123456789".equals(contact.getPhone())){
			isExist = true;
		}
		return new Boolean(isExist).toString();
		
	}
</pre>
<p><strong>8.	we can see the description of all Web services using </strong><br />
http://localhost:8080/contacts/rest/application.wadl url.</p>
<pre name="code" class="xml">
<application xmlns="http://wadl.dev.java.net/2009/02">
<doc xmlns:jersey="http://jersey.java.net/" jersey:generatedBy="Jersey: 1.14 09/09/2012 05:39 PM"/>
<grammars>
<include href="application.wadl/xsd0.xsd">
<doc xml:lang="en" title="Generated"/>
</include>
</grammars>
<resources base="http://localhost:8080/contacts/rest/">
<resource path="contact">
<resource path="getInfo">
<method name="GET" id="getInfo">
<response>
<representation mediaType="text/plain"/>
</response>
</method>
</resource>
<resource path="getJsonContact">
<method name="GET" id="getJsonContact">
<response>
<ns2:representation xmlns:ns2="http://wadl.dev.java.net/2009/02" xmlns="" mediaType="application/json" element="contact"/>
</response>
</method>
</resource>
<resource path="getXmlContact">
<method name="GET" id="getXmlContact">
<response>
<ns2:representation xmlns:ns2="http://wadl.dev.java.net/2009/02" xmlns="" mediaType="application/xml" element="contact"/>
</response>
</method>
</resource>
<resource path="{id}">
<param xmlns:xs="http://www.w3.org/2001/XMLSchema" type="xs:string" style="template" name="id"/>
<method name="GET" id="getJsonContactPathId">
<response>
<ns2:representation xmlns:ns2="http://wadl.dev.java.net/2009/02" xmlns="" mediaType="application/json" element="contact"/>
</response>
</method>
</resource>
<resource path="getContactWithId">
<method name="GET" id="getJsonContactQueryId">
<request>
<param xmlns:xs="http://www.w3.org/2001/XMLSchema" type="xs:string" style="query" name="id"/>
</request>
<response>
<ns2:representation xmlns:ns2="http://wadl.dev.java.net/2009/02" xmlns="" mediaType="application/json" element="contact"/>
</response>
</method>
</resource>
<resource path="isContactExist">
<method name="POST" id="isContactExist">
<request>
<ns2:representation xmlns:ns2="http://wadl.dev.java.net/2009/02" xmlns="" mediaType="application/json" element="contact"/>
</request>
<response>
<representation mediaType="text/plain"/>
</response>
</method>
</resource>
</resource>
</resources>
</application>
</pre>
<p>This is just a basic introduction of web service development using jersey. We can do lots of things like saving  and fetching contacts from db, etc. For maintaining simplicity i didn&#8217;t handled error cases in the code.</p>
<h4>Incoming search terms:</h4><ul><li><a href="http://blog.vimviv.com/web/creating-restful-web-services-jersey/" title="rest webservice java jersey eclipse">rest webservice java jersey eclipse</a> (3)</li><li><a href="http://blog.vimviv.com/web/creating-restful-web-services-jersey/" title="how to create jersey restful webservice in eclipse">how to create jersey restful webservice in eclipse</a> (2)</li><li><a href="http://blog.vimviv.com/web/creating-restful-web-services-jersey/" title="login validation using jersy restful webservice">login validation using jersy restful webservice</a> (2)</li><li><a href="http://blog.vimviv.com/web/creating-restful-web-services-jersey/" title="restful web services using jersey in eclipse">restful web services using jersey in eclipse</a> (2)</li><li><a href="http://blog.vimviv.com/web/creating-restful-web-services-jersey/" title="@post @consumes(mediatype application_json) @produces(mediatype text_plain)">@post @consumes(mediatype application_json) @produces(mediatype text_plain)</a> (2)</li><li><a href="http://blog.vimviv.com/web/creating-restful-web-services-jersey/" title="jersey produces delete consume">jersey produces delete consume</a> (1)</li><li><a href="http://blog.vimviv.com/web/creating-restful-web-services-jersey/" title="jersey rest books">jersey rest books</a> (1)</li><li><a href="http://blog.vimviv.com/web/creating-restful-web-services-jersey/" title="jersey REST service return XML output">jersey REST service return XML output</a> (1)</li><li><a href="http://blog.vimviv.com/web/creating-restful-web-services-jersey/" title="jersey rest web service client conversion to json">jersey rest web service client conversion to json</a> (1)</li><li><a href="http://blog.vimviv.com/web/creating-restful-web-services-jersey/" title="Jersey web service consumes JSON blog">Jersey web service consumes JSON blog</a> (1)</li></ul><div class='yarpp-related-rss yarpp-related-none'>
<p>No related posts.</p>
<img src='http://yarpp.org/pixels/29e3c972243f67e94906e1c79d9a0b70'/>
</div>
<img src="http://feeds.feedburner.com/~r/vimviv/~4/maEud-CYSko" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.vimviv.com/web/creating-restful-web-services-jersey/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.vimviv.com/web/creating-restful-web-services-jersey/</feedburner:origLink></item>
		<item>
		<title>voice command example using proximity sensor, voice recognizer and TTS in android</title>
		<link>http://feedproxy.google.com/~r/vimviv/~3/jY5Ol0NtMeU/</link>
		<comments>http://blog.vimviv.com/android/proximity-sensor-voice-recognizer-tts-android/#comments</comments>
		<pubDate>Sat, 19 Nov 2011 10:51:01 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
				<category><![CDATA[Android]]></category>

		<guid isPermaLink="false">http://blog.vimviv.com/?p=554</guid>
		<description><![CDATA[In this example we will combine some features of android like proximity sensor, voice recognizer and TTS. Proximity Sensor: is sensor that can recognize presence of nearby object. we will user this sensor to start voice recognition. So when you take you android device near to your face, proximity sensor will start the voice recognizer. [...]<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href='http://blog.vimviv.com/android/intent-android/' rel='bookmark' title='What is Intent in android?'>What is Intent in android?</a></li>
<li><a href='http://blog.vimviv.com/android/prompt-user-enable-location-providers-android/' rel='bookmark' title='Prompt user to enable location providers in Android'>Prompt user to enable location providers in Android</a></li>
<li><a href='http://blog.vimviv.com/android/intent-filter-android/' rel='bookmark' title='What is intent filter in android?'>What is intent filter in android?</a></li>
</ol>
<img src='http://yarpp.org/pixels/29e3c972243f67e94906e1c79d9a0b70'/>
</div>
]]></description>
				<content:encoded><![CDATA[<p>In this example we will combine some features of android like proximity sensor, voice recognizer and TTS.</p>
<p><strong>Proximity Sensor:</strong> is sensor that can recognize presence of nearby object. we will user this sensor to start voice recognition. So when you take you android device near to your face, proximity sensor will start the voice recognizer.</p>
<p><strong>Voice Recognizer: </strong>can convert speech to text. So when you give the voice command, its will return an array of matches and will start TTS.</p>
<p><strong>TTS(Text To Speech):</strong> can convert text speech. In this application we will use TTS to listen voice command response.<br />
<span id="more-554"></span><br />
<strong>1.</strong> First we will check to see if proximity sensor is available.</p>
<pre name="code" class="java">
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		Sensor proximitySensor = sensorManager
				.getDefaultSensor(Sensor.TYPE_PROXIMITY);

		if (proximitySensor == null) {
			Toast.makeText(this, "No proximity sensor", Toast.LENGTH_SHORT)
					.show();
		} else {
			sensorManager.registerListener(proximitySensorEventListener,
					proximitySensor, SensorManager.SENSOR_DELAY_NORMAL);
		}
</pre>
<p><strong>2.</strong> We will catch proximity event in onSensorChanged callback method in proximitySensorEventListener.</p>
<pre name="code" class="java">
SensorEventListener proximitySensorEventListener = new SensorEventListener() {

		@Override
		public void onAccuracyChanged(Sensor sensor, int accuracy) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onSensorChanged(SensorEvent event) {
			if (event.sensor.getType() == Sensor.TYPE_PROXIMITY) {
				if (event.values[0] < proximitySensor.getMaximumRange()) {
					startSpeechRecognizer();
				}

			}
		}
	};
</pre>
<p><strong>3.</strong> Start speech recognizer, when any object comes near to mobile.</p>
<pre name="code" class="java">
private static final int VOICE_REQUEST_CODE = 101;
private void startSpeechRecognizer() {
		PackageManager pm = getPackageManager();
		List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
				RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
		if (activities.size() != 0) {
		Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
		intent.putExtra(RecognizerIntent.ACTION_RECOGNIZE_SPEECH,
				RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
		intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Voice Command");
		startActivityForResult(intent, VOICE_REQUEST_CODE);
		}else{
			Toast.makeText(this, "Speech Recognizer is not present", Toast.LENGTH_SHORT)
			.show();
		}

	}
</pre>
<p><strong>Explanation of above code:</strong><br />
<strong>queryIntentActivities:</strong> will return the list of activities that can handle action ACTION_RECOGNIZE_SPEECH.<br />
<strong>ACTION_RECOGNIZE_SPEECH:</strong> start implicit activity that can handle action ACTION_RECOGNIZE_SPEECH.<br />
<strong>EXTRA_PROMPT:</strong> It will show custom message "Voice Command" on voice recognizer activity.<br />
<a href="http://i1.wp.com/blog.vimviv.com/wp-content/uploads/2011/11/voice-command.png"><img src="http://i1.wp.com/blog.vimviv.com/wp-content/uploads/2011/11/voice-command.png?resize=320%2C480" alt="Voice Command" title="voice-command" class="aligncenter size-full wp-image-559" data-recalc-dims="1" /></a><br />
<strong>4.</strong> We will get result of speech recognizer in onActivityResult callback.</p>
<pre name="code" class="java">
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == VOICE_REQUEST_CODE &#038;&#038; resultCode == RESULT_OK) {
			ArrayList<String> matches = data
					.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
			for (int i = 0; i < commands.length; i++) {
				if (matches.contains(commands[i])) {
					selectedCommand = i;
				}
			}
			if (isTtsInitialized) {
				if (selectedCommand >= 0) {
					tts.speak("you have selected" + commands[selectedCommand]
							+ " command.", TextToSpeech.QUEUE_FLUSH, null);
				} else {
					tts.speak("I am sorry. could you please repeat that.", TextToSpeech.QUEUE_FLUSH, null);
				}

			}

		}
}
</pre>
<p><strong>Explanation of above code:</strong></p>
<p><strong>requestCode and resultCode:</strong> first we will check requestCode and resultCode to insure that onActivityResult is called by speech recognizer with success response.<br />
<strong>getStringArrayListExtra:</strong> We will get all matches using getStringArrayListExtra. If matches contains our commands, TTS will say that otherwise it will say "I am sorry. could you please repeat that.".</p>
<p><strong>5.</strong> We will check to see if TTS is present. First we need to implement OnInitListener and override onInit method.</p>
<pre name="code" class="java">
@Override
	public void onInit(int status) {
		if (status == TextToSpeech.SUCCESS) {
			int result = tts.setLanguage(Locale.US);
			if (result == TextToSpeech.LANG_MISSING_DATA
					|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
				Toast.makeText(this, "Language is not available",
						Toast.LENGTH_SHORT);
			} else {
				isTtsInitialized = true;
			}
		} else {
			Toast.makeText(this, "Initialization failed", Toast.LENGTH_SHORT);
		}

	}
</pre>
<p>After completion of TTS engine initialization start the TTs.</p>
<pre name="code" class="java">
Intent checkIntent = new Intent();
		checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
		startActivityForResult(checkIntent, TTS_REQUEST_CODE);
</pre>
<p><strong>6.</strong> We will get response in onActivityResult.</p>
<pre name="code" class="java">
@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		if (requestCode == TTS_REQUEST_CODE) {
			if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
				// success, create the TTS instance
				tts = new TextToSpeech(this, this);
			} else {
				// missing data, install it
				Intent installIntent = new Intent();
				installIntent
						.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
				startActivity(installIntent);
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
</pre>
<p><strong>7.</strong> Don't forget to unregister proximity sensor listener.</p>
<pre name="code" class="java">
@Override
	protected void onStop() {
		if (sensorManager != null) {
			sensorManager.unregisterListener(proximitySensorEventListener);
		}
		super.onStop();
	}
</pre>
<p>Instead of just listening the commands we can do lots of things like opening address book, messages, mails, etc. Here is the complete code.</p>
<pre name="code" class="java">
package com.vimviv;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.widget.Toast;

public class VoiceCommandActivity extends Activity implements OnInitListener {

	private static final int VOICE_REQUEST_CODE = 101;
	private static final int TTS_REQUEST_CODE = 102;
	private static final String[] commands = { "open", "close", "find" };

	private int selectedCommand = -1;
	private String speachMessage = "I am sorry. could you please repeat that.";
	private boolean isTtsInitialized = false;
	TextToSpeech tts;
	SensorManager sensorManager;
	Sensor proximitySensor;

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

		// check proximity sensor
		sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		proximitySensor = sensorManager
				.getDefaultSensor(Sensor.TYPE_PROXIMITY);

		if (proximitySensor == null) {
			Toast.makeText(this, "No proximity sensor", Toast.LENGTH_SHORT)
					.show();
		} else {
			sensorManager.registerListener(proximitySensorEventListener,
					proximitySensor, SensorManager.SENSOR_DELAY_NORMAL);
		}
		
		//check for TTS data
		Intent checkIntent = new Intent();
		checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
		startActivityForResult(checkIntent, TTS_REQUEST_CODE);

	}

	SensorEventListener proximitySensorEventListener = new SensorEventListener() {

		@Override
		public void onAccuracyChanged(Sensor sensor, int accuracy) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onSensorChanged(SensorEvent event) {
			// TODO Auto-generated method stub

			if (event.sensor.getType() == Sensor.TYPE_PROXIMITY) {
				if (event.values[0] < proximitySensor.getMaximumRange()) {
					startSpeachRecognition();
				}

			}
		}
	};

	private void startSpeachRecognition() {
		// Check to see if a recognition activity is present
				PackageManager pm = getPackageManager();
				List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
						RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
				if (activities.size() != 0) {
					Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
					intent.putExtra(RecognizerIntent.ACTION_RECOGNIZE_SPEECH,
							RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
					intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Voice Command");
					startActivityForResult(intent, VOICE_REQUEST_CODE);
				} else {
					Toast.makeText(this, "Recognizer not present", Toast.LENGTH_SHORT)
					.show();
				}

		

	}
	
	// Initialization response of TTS engine
	@Override
	public void onInit(int status) {
		if (status == TextToSpeech.SUCCESS) {
			int result = tts.setLanguage(Locale.US);
			if (result == TextToSpeech.LANG_MISSING_DATA
					|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
				Toast.makeText(this, "Language is not available",
						Toast.LENGTH_SHORT);
			} else {
				isTtsInitialized = true;
			}
		} else {
			Toast.makeText(this, "Initialization failed", Toast.LENGTH_SHORT);
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == VOICE_REQUEST_CODE &#038;&#038; resultCode == RESULT_OK) {
			ArrayList<String> matches = data
					.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
			for (int i = 0; i < commands.length; i++) {
				if (matches.contains(commands[i])) {
					selectedCommand = i;
				}
			}
			if (isTtsInitialized) {
				if (selectedCommand >= 0) {
					tts.speak("you have selected" + commands[selectedCommand]
							+ " command.", TextToSpeech.QUEUE_FLUSH, null);
					selectedCommand = -1;
				} else {
					tts.speak(speachMessage, TextToSpeech.QUEUE_FLUSH, null);
				}

			}

		}
		if (requestCode == TTS_REQUEST_CODE) {
			if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
				// success, create the TTS instance
				tts = new TextToSpeech(this, this);
			} else {
				// missing data, install it
				Intent installIntent = new Intent();
				installIntent
						.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
				startActivity(installIntent);
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void onStop() {
		if (sensorManager != null) {
			sensorManager.unregisterListener(proximitySensorEventListener);
		}
		super.onStop();
	}

	
}
</pre>
<h4>Incoming search terms:</h4><ul><li><a href="http://blog.vimviv.com/android/proximity-sensor-voice-recognizer-tts-android/" title="voice command">voice command</a> (64)</li><li><a href="http://blog.vimviv.com/android/proximity-sensor-voice-recognizer-tts-android/" title="android proximity sensor example">android proximity sensor example</a> (45)</li><li><a href="http://blog.vimviv.com/android/proximity-sensor-voice-recognizer-tts-android/" title="proximity sensor android example">proximity sensor android example</a> (31)</li><li><a href="http://blog.vimviv.com/android/proximity-sensor-voice-recognizer-tts-android/" title="RecognizerIntent ACTION_RECOGNIZE_SPEECH">RecognizerIntent ACTION_RECOGNIZE_SPEECH</a> (26)</li><li><a href="http://blog.vimviv.com/android/proximity-sensor-voice-recognizer-tts-android/" title="voice command sensor">voice command sensor</a> (17)</li><li><a href="http://blog.vimviv.com/android/proximity-sensor-voice-recognizer-tts-android/" title="android: example on proximity sensor">android: example on proximity sensor</a> (14)</li><li><a href="http://blog.vimviv.com/android/proximity-sensor-voice-recognizer-tts-android/" title="proximity sensor example in android">proximity sensor example in android</a> (13)</li><li><a href="http://blog.vimviv.com/android/proximity-sensor-voice-recognizer-tts-android/" title="action_recognize_speech">action_recognize_speech</a> (10)</li><li><a href="http://blog.vimviv.com/android/proximity-sensor-voice-recognizer-tts-android/" title="android ACTION_RECOGNIZE_SPEECH">android ACTION_RECOGNIZE_SPEECH</a> (4)</li><li><a href="http://blog.vimviv.com/android/proximity-sensor-voice-recognizer-tts-android/" title="proximity toast">proximity toast</a> (3)</li></ul><div class='yarpp-related-rss'>
<p>Related posts:</p><ol>
<li><a href='http://blog.vimviv.com/android/intent-android/' rel='bookmark' title='What is Intent in android?'>What is Intent in android?</a></li>
<li><a href='http://blog.vimviv.com/android/prompt-user-enable-location-providers-android/' rel='bookmark' title='Prompt user to enable location providers in Android'>Prompt user to enable location providers in Android</a></li>
<li><a href='http://blog.vimviv.com/android/intent-filter-android/' rel='bookmark' title='What is intent filter in android?'>What is intent filter in android?</a></li>
</ol>
<img src='http://yarpp.org/pixels/29e3c972243f67e94906e1c79d9a0b70'/>
</div>
<img src="http://feeds.feedburner.com/~r/vimviv/~4/jY5Ol0NtMeU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.vimviv.com/android/proximity-sensor-voice-recognizer-tts-android/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://blog.vimviv.com/android/proximity-sensor-voice-recognizer-tts-android/</feedburner:origLink></item>
		<item>
		<title>What is intent filter in android?</title>
		<link>http://feedproxy.google.com/~r/vimviv/~3/KW5H188Mq-Q/</link>
		<comments>http://blog.vimviv.com/android/intent-filter-android/#comments</comments>
		<pubDate>Thu, 10 Nov 2011 15:35:49 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
				<category><![CDATA[Android]]></category>

		<guid isPermaLink="false">http://blog.vimviv.com/?p=534</guid>
		<description><![CDATA[In my previous post, What is Intent in android? I have disused about intents. In that post we have seen that there are two types of intents. 1. Explicit intents: We can call target component by its name. 2. implicit intents: We can call a target component on the basis of what we want to [...]<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href='http://blog.vimviv.com/android/intent-android/' rel='bookmark' title='What is Intent in android?'>What is Intent in android?</a></li>
<li><a href='http://blog.vimviv.com/android/prompt-user-enable-location-providers-android/' rel='bookmark' title='Prompt user to enable location providers in Android'>Prompt user to enable location providers in Android</a></li>
<li><a href='http://blog.vimviv.com/android/started-android/' rel='bookmark' title='Getting Started With Android'>Getting Started With Android</a></li>
</ol>
<img src='http://yarpp.org/pixels/29e3c972243f67e94906e1c79d9a0b70'/>
</div>
]]></description>
				<content:encoded><![CDATA[<p>In my previous post, <a href="http://blog.vimviv.com/android/intent-android/">What is Intent in android?</a> I have disused about intents. In that post we have seen that there are two types of intents.<br />
<strong>1. Explicit intents:</strong> We can call target component by its name.<br />
<strong>2. implicit intents:</strong> We can call a target component on the basis of what we want to perform.</p>
<p>In this post we will see, how does implicit intent work?<br />
According to google  intent filter is &#8220;To inform the system which implicit intents they can handle&#8221;</p>
<p>e.g. you have more that one activities in your application  and you know that there is no &#8220;main&#8221; method in android application. So how activity launcher will know that which activity to start first.<br />
<span id="more-534"></span><br />
For that we specify a intent filter.</p>
<pre name="code" class="xml">
<activity android:name=".HomeActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
</pre>
<p>intent filter with &#8220;android.intent.action.MAIN&#8221; action and &#8220;android.intent.category.LAUNCHER&#8221; category tells to launcher to launch HomeActivity.</p>
<p>implicit Intent is luxury provided by android. You just need to know, what do you want to perform. you don&#8217;t bother who is going to perform and how that activity is going to perform.(there will be a problem, if no activity is there to perform your task)</p>
<p><strong>When will you specify intent filter?</strong><br />
if you think, any other application can use your activity to perform some task, specify a intent filter for that. You can be a performer using intent filter.</p>
<p>For example, you have created a activity that can display image and you think that other applications also use your activity to view images.</p>
<p><strong>1.</strong> specify intent filter like this.</p>
<pre name="code" class="xml">
<activity
            android:label="@string/app_name"
            android:name=".MyImageViewerActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter >
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />

                <data android:mimeType="image/*" />
            </intent-filter>
</pre>
<p>In the above code we can see that intent-filter has following properties.<br />
<strong>a. action: </strong>type for which this activity will respond for.Like this activity will respond for view action.<br />
<strong>b. category: </strong>implicit intents are divided in categories.Like this activity is in default category.<br />
<strong>c. data: </strong>Specify more information about intent-filter. Like this activity will handle file of mimeType &#8220;image/*&#8221;.</p>
<p><strong>2.</strong> Now you need to display image in your activity.</p>
<pre name="code" class="java">
public class MyImageViewerActivity extends Activity {
	
	TextView textView;
	ImageView imageView;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Intent intent = getIntent();
        Uri uri = intent.getData();
        
        textView = (TextView) findViewById(R.id.textView);
        imageView = (ImageView) findViewById(R.id.imageView);
        
        if(uri != null){
        	imageView.setImageURI(uri);
        	textView.setText(uri.getPath());
        }
        
        
    }
}
</pre>
<p>using getData() we will get the path of the image and we will use that path to display image. </p>
<p><strong>3. </strong>When you install this application in your device and click on any image file, you will see a choice dialog that offer you to select between default application and your application. Just select your application to see the image.</p>
<p><a href="http://i1.wp.com/blog.vimviv.com/wp-content/uploads/2011/11/intent-filter.png"><img src="http://i1.wp.com/blog.vimviv.com/wp-content/uploads/2011/11/intent-filter.png?resize=320%2C480" alt="intent filter choice dailog" title="intent-filter" class="aligncenter size-full wp-image-535" data-recalc-dims="1" /></a></p>
<p><strong>4.</strong> Just select your app to view image:</p>
<p><a href="http://i1.wp.com/blog.vimviv.com/wp-content/uploads/2011/11/intent-filter-activity1.png"><img src="http://i1.wp.com/blog.vimviv.com/wp-content/uploads/2011/11/intent-filter-activity1.png?resize=320%2C480" alt="intent filter activity" title="intent filter activity" class="aligncenter size-full wp-image-543" data-recalc-dims="1" /></a><br />
<strong>When will you call implicit intent?</strong><br />
If you think that any other activity is available in device for handling your application&#8217;s specific task, just use the implicit intent to call that activity.</p>
<p>For example, if you want to open a browser to render URI. You can use implicit intent to call browser.</p>
<pre name="code" class="java">
Uri uri = Uri.parse( "http://blog.vimviv.com" );
startActivity(new Intent(Intent.ACTION_VIEW, uri));
</pre>
<p>In above example we can see that we have a uri and we want to view content of that uri. We don&#8217;t need to know that which activity is going to render this uri.</p>
<p><strong>Some more examples of intent filters.</strong><br />
a) intent filter for app launcher</p>
<pre name="code" class="xml">
			<intent-filter>
				<action android:name="android.intent.action.MAIN" />
				<category android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
</pre>
<p>b)intent filter for image view.</p>
<pre name="code" class="xml">
			<intent-filter>
				<action android:name="android.intent.action.VIEW" />
				<category android:name="android.intent.category.DEFAULT" />
				<data android:mimeType="image/*" />
			</intent-filter>
</pre>
<p>c)intent filter for image send:</p>
<pre name="code" class="xml">
			<intent-filter>
				<action android:name="android.intent.action.SEND" />
				<category android:name="android.intent.category.DEFAULT" />
				<data android:mimeType="image/*" />
			</intent-filter>
</pre>
<p>d) intent filter for custom uri:</p>
<pre name="code" class="xml">
			<intent-filter>
				<action android:name="android.intent.action.VIEW" />
				<category android:name="android.intent.category.DEFAULT" />
				<category android:name="android.intent.category.BROWSABLE" />
				<data android:scheme="myapp" android:host="path" />
			</intent-filter>
</pre>
<p>e) intent filter for sms:</p>
<pre name="code" class="xml">
			<intent-filter>
				<action android:name="android.intent.action.VIEW" />
				<action android:name="android.intent.action.SENDTO" />
				<category android:name="android.intent.category.DEFAULT" />
				<category android:name="android.intent.category.BROWSABLE" />
				<data android:scheme="sms" />
				<data android:scheme="smsto" />
			</intent-filter>
</pre>
<p>f)intent filter phone dial:</p>
<pre name="code" class="xml">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <action android:name="android.intent.action.DIAL" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="tel" />
            </intent-filter>
           </pre>
<p>Some examples for calling implicit intents:<br />
a) start contacts activity:</p>
<pre name="code" class="java">
Intent contacts = new Intent();
              contacts.setAction(android.content.Intent.ACTION_VIEW);
              contacts.setData(People.CONTENT_URI);
              startActivity(contacts);
</pre>
<p>b) install an app:</p>
<pre name="code" class="java">
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "app.apk")), "application/vnd.android.package-archive");
startActivity(intent);  
</pre>
<p>c) uninstall an app:</p>
<pre name="code" class="java">
Uri packageUri = Uri.parse("package:com.vimviv");
            Intent uninstallIntent =
              new Intent(Intent. ACTION_DELETE, packageUri);
            startActivity(uninstallIntent);
</pre>
<p>d) start sms application:</p>
<pre name="code" class="java">
Intent sendIntent = new Intent(Intent.ACTION_VIEW);         
sendIntent.setData(Uri.parse("sms:"));
</pre>
<p>We can also search for a matching intent:</p>
<pre name="code" class="java">
final PackageManager packageManager = context.getPackageManager();
    final Intent intent = new Intent(action);
    List<ResolveInfo> list =
            packageManager.queryIntentActivities(intent,
                    PackageManager.MATCH_DEFAULT_ONLY);
    return list.size() > 0;

</pre>
<p>So help others by creating re-usable activities.</p>
<h4>Incoming search terms:</h4><ul><li><a href="http://blog.vimviv.com/android/intent-filter-android/" title="what is intent filter in android">what is intent filter in android</a> (78)</li><li><a href="http://blog.vimviv.com/android/intent-filter-android/" title="what is the use of intent filter in android">what is the use of intent filter in android</a> (8)</li><li><a href="http://blog.vimviv.com/android/intent-filter-android/" title="intent filter in android example">intent filter in android example</a> (6)</li><li><a href="http://blog.vimviv.com/android/intent-filter-android/" title="intent filter example">intent filter example</a> (6)</li><li><a href="http://blog.vimviv.com/android/intent-filter-android/" title="what is intent filter">what is intent filter</a> (3)</li><li><a href="http://blog.vimviv.com/android/intent-filter-android/" title="what is intent filters in android">what is intent filters in android</a> (3)</li><li><a href="http://blog.vimviv.com/android/intent-filter-android/" title="intent mimeType=image/* getintent">intent mimeType=image/* getintent</a> (2)</li><li><a href="http://blog.vimviv.com/android/intent-filter-android/" title="what is intent in android and what is intent filter in android">what is intent in android and what is intent filter in android</a> (2)</li><li><a href="http://blog.vimviv.com/android/intent-filter-android/" title="intent filter for action view">intent filter for action view</a> (2)</li><li><a href="http://blog.vimviv.com/android/intent-filter-android/" title="what is intentfilter in android">what is intentfilter in android</a> (2)</li></ul><div class='yarpp-related-rss'>
<p>Related posts:</p><ol>
<li><a href='http://blog.vimviv.com/android/intent-android/' rel='bookmark' title='What is Intent in android?'>What is Intent in android?</a></li>
<li><a href='http://blog.vimviv.com/android/prompt-user-enable-location-providers-android/' rel='bookmark' title='Prompt user to enable location providers in Android'>Prompt user to enable location providers in Android</a></li>
<li><a href='http://blog.vimviv.com/android/started-android/' rel='bookmark' title='Getting Started With Android'>Getting Started With Android</a></li>
</ol>
<img src='http://yarpp.org/pixels/29e3c972243f67e94906e1c79d9a0b70'/>
</div>
<img src="http://feeds.feedburner.com/~r/vimviv/~4/KW5H188Mq-Q" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.vimviv.com/android/intent-filter-android/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://blog.vimviv.com/android/intent-filter-android/</feedburner:origLink></item>
		<item>
		<title>Custom Annotation in Android</title>
		<link>http://feedproxy.google.com/~r/vimviv/~3/t_v8eF2Y2os/</link>
		<comments>http://blog.vimviv.com/android/custom-annotation-android/#comments</comments>
		<pubDate>Fri, 14 Oct 2011 15:33:02 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
				<category><![CDATA[Android]]></category>

		<guid isPermaLink="false">http://blog.vimviv.com/?p=522</guid>
		<description><![CDATA[For definition of java annotation i can&#8217;t think a better definition than wikipedia &#8220;An annotation, in the Java computer programming language, is a special form of syntactic metadata that can be added to Java source code. Classes, methods, variables, parameters and packages may be annotated. Unlike Javadoc tags, Java annotations can be reflective in that [...]<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href='http://blog.vimviv.com/android/started-android/' rel='bookmark' title='Getting Started With Android'>Getting Started With Android</a></li>
</ol>
<img src='http://yarpp.org/pixels/29e3c972243f67e94906e1c79d9a0b70'/>
</div>
]]></description>
				<content:encoded><![CDATA[<p>For definition of java annotation i can&#8217;t think a better definition than wikipedia &#8220;An annotation, in the Java computer programming language, is a special form of syntactic metadata that can be added to Java source code. Classes, methods, variables, parameters and packages may be annotated. Unlike Javadoc tags, Java annotations can be reflective in that they can be embedded in class files generated by the compiler and may be retained by the Java VM to be made retrievable at run-time.&#8221; <a href="http://en.wikipedia.org/wiki/Java_annotation">http://en.wikipedia.org/wiki/Java_annotation</a>  Some of  the java programmers use annotations without even know about annotations. When ever you override any method of super class in you class, eclipse automatically adds the @override annotation above method name.<br />
<span id="more-522"></span><br />
 e.g.</p>
<pre name="code" class="java">
@Override
    public String toString() {
    	return super.toString();
    }
</pre>
<p>In the above example code,<br />
<strong>@Override: </strong>gives the information that toString() method is overridden from Object class.<br />
In this post we will create custom annotations.   </p>
<p>1. First we will create a custom annotation for Database table name.</p>
<pre name="code" class="java">
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface DatabaseTable {

	String tableName();
}
</pre>
<p>Explanation of above code:<br />
<strong>@interface:</strong> We can see in the above code is similar to interface declaration. <strong>@Retention(RetentionPolicy.RUNTIME):</strong> We need this annotation type at runtime. We are using RetentionPolicy.RUNTIME.<br />
<strong>@Target(ElementType.TYPE): </strong> Indicates that this annotation type will be used to annotate class declaration  </p>
<p>2. Next we will create another annotation for column names.</p>
<pre name="code" class="java">
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface DatabaseField {

	String columnName() default "";
	String columnType();
	boolean canBeNull() default true;

}
</pre>
<p>Explanation of above code:<br />
<strong>@Target(ElementType.FIELD):</strong> Indicates that this annotation type will used to annotate fields declarations.<br />
<strong>default:</strong> is used to assign default value.  </p>
<p>3. We will create UserInfo class that we want to save in database.</p>
<pre name="code" class="java">
@DatabaseTable (tableName = "user")
public class UserData {

	@DatabaseField (columnName = "first_name", columnType ="TEXT")
	private String firstName;
	@DatabaseField (columnName = "last_name", columnType ="TEXT")
	private String lastName;
	@DatabaseField (columnName = "age", columnType ="INTEGER")
	private int age;

}
</pre>
<p>4. Create query for create table.</p>
<pre name="code" class="java">
public String createTableQuery(Class clazz){
		DatabaseTable annot = (DatabaseTable) clazz.getAnnotation(DatabaseTable.class);
		String table = annot.tableName();
		Field[] fields = clazz.getDeclaredFields();
		StringBuilder sb = new StringBuilder("CREATE TABLE ").append(table).append(
						" (_id integer primary key");
				for (Field field : fields) {
					DatabaseField fieldAnnot = (DatabaseField) field.getAnnotation(DatabaseField.class);
					String columnName = fieldAnnot.columnName();
					String columnType = fieldAnnot.columnType();
					sb.append(", ").append(columnName).append(" ").append(columnType);
				}
				sb.append(")");
				return sb.toString();
		}
</pre>
<p>5. We will call this method like this</p>
<pre name="code" class="java">
String sqlQuery = createTableQuery(UserInfo.Class);
</pre>
<p>Complete implementation of ORM(object relational mapping) is complex. You can check  <a href="http://ormlite.com/">OrmLite &#8211; Lightweight Object Relational Mapping (ORM) Java Package </a>for complete annotation based ORM implementation.   </p>
<p>We can also search at run time about annotated classes.</p>
<pre name="code" class="java">
public static List getModels(Context context, String packageName)
			throws IOException, URISyntaxException, ClassNotFoundException,
			NameNotFoundException {

		String apkName = context.getPackageManager().getApplicationInfo(packageName, 0).sourceDir;
		DexFile dexFile = new DexFile(apkName);
		PathClassLoader pathLoader = new PathClassLoader(apkName, Thread.currentThread().getContextClassLoader());
		DexClassLoader classLoader = new DexClassLoader(apkName,
				new ContextWrapper(context).getCacheDir().getAbsolutePath(),
				null, pathLoader);
		List classes = new ArrayList();
		Enumeration entries = dexFile.entries();

		while (entries.hasMoreElements()) {

			String entry = (String) entries.nextElement();

			if (entry.startsWith(packageName)) {
				Class entryClass = classLoader.loadClass(entry);
				if (entryClass != null) {
					Annotation[] annotations = entryClass.getAnnotations();
					for (Annotation annotation : annotations) {
						if (annotation instanceof DatabaseTable) {
							classes.add(entryClass);
						}
					}
				}
			}
		}

		return classes;
	}
</pre>
<p>This was a small example of custom annotation. We can use custom annotations in a lots of ways like configuration, unit testing, etc.</p>
<h4>Incoming search terms:</h4><ul><li><a href="http://blog.vimviv.com/android/custom-annotation-android/" title="android annotation example">android annotation example</a> (46)</li><li><a href="http://blog.vimviv.com/android/custom-annotation-android/" title="android annotation">android annotation</a> (24)</li><li><a href="http://blog.vimviv.com/android/custom-annotation-android/" title="android custom annotation">android custom annotation</a> (19)</li><li><a href="http://blog.vimviv.com/android/custom-annotation-android/" title="android custom annotations">android custom annotations</a> (10)</li><li><a href="http://blog.vimviv.com/android/custom-annotation-android/" title="annotation example in android">annotation example in android</a> (7)</li><li><a href="http://blog.vimviv.com/android/custom-annotation-android/" title="how to use annotations in android example">how to use annotations in android example</a> (2)</li><li><a href="http://blog.vimviv.com/android/custom-annotation-android/" title="android create custom annotations in android">android create custom annotations in android</a> (2)</li><li><a href="http://blog.vimviv.com/android/custom-annotation-android/" title="android annotation examples">android annotation examples</a> (2)</li><li><a href="http://blog.vimviv.com/android/custom-annotation-android/" title="annotation tutorial android">annotation tutorial android</a> (2)</li><li><a href="http://blog.vimviv.com/android/custom-annotation-android/" title="custom annotation overlay android">custom annotation overlay android</a> (1)</li></ul><div class='yarpp-related-rss'>
<p>Related posts:</p><ol>
<li><a href='http://blog.vimviv.com/android/started-android/' rel='bookmark' title='Getting Started With Android'>Getting Started With Android</a></li>
</ol>
<img src='http://yarpp.org/pixels/29e3c972243f67e94906e1c79d9a0b70'/>
</div>
<img src="http://feeds.feedburner.com/~r/vimviv/~4/t_v8eF2Y2os" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.vimviv.com/android/custom-annotation-android/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://blog.vimviv.com/android/custom-annotation-android/</feedburner:origLink></item>
		<item>
		<title>Prompt user to enable location providers in Android</title>
		<link>http://feedproxy.google.com/~r/vimviv/~3/Q6hJT9sfgy0/</link>
		<comments>http://blog.vimviv.com/android/prompt-user-enable-location-providers-android/#comments</comments>
		<pubDate>Wed, 13 Jul 2011 17:26:55 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
				<category><![CDATA[Android]]></category>

		<guid isPermaLink="false">http://blog.vimviv.com/?p=511</guid>
		<description><![CDATA[Now a days almost every smartphone applications use location based functionalities. But every articles say that disable wifi, 3g, gps etc for battery saving. So for every location based applications lots of problems are there like. What are location providers available in device? You can enable GPS using some method but best methods is ask [...]<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href='http://blog.vimviv.com/blackberry/location-gps-blackberry/' rel='bookmark' title='How to get location without GPS in Blackberry'>How to get location without GPS in Blackberry</a></li>
<li><a href='http://blog.vimviv.com/android/android-some-basic-keywords/' rel='bookmark' title='Android &#8211; some basic keywords'>Android &#8211; some basic keywords</a></li>
<li><a href='http://blog.vimviv.com/android/intent-android/' rel='bookmark' title='What is Intent in android?'>What is Intent in android?</a></li>
</ol>
<img src='http://yarpp.org/pixels/29e3c972243f67e94906e1c79d9a0b70'/>
</div>
]]></description>
				<content:encoded><![CDATA[<p>Now a days almost every smartphone applications use location based functionalities. But every articles say that disable wifi, 3g, gps etc for battery saving. So for every location based applications lots of problems are there like. What are location providers available in device? You can enable GPS using some method but best methods is ask user to enable location providers.<br />
In this post we will see that how can we prompt user to enable location providers.<br />
<span id="more-511"></span></p>
<pre name="code" class="java"> 
 private void checkLocationProviders(){
	    //String provider = Settings.Secure.getString(getContentResolver(),Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
	       if(lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
	    	   
	    	   Toast.makeText(EnableLocationActivity.this, "GPS provider Enabled: ",Toast.LENGTH_LONG).show();
	        
	       }else if(lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
	    	   
	    	   Toast.makeText(EnableLocationActivity.this, "Network provider Enabled: ",Toast.LENGTH_LONG).show();
	    	   
	       }else{
	    	   AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    	   builder.setMessage("Location providers are not available. Enable GPS or network providers.")
	    	          .setCancelable(false)
	    	          .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
	    	              public void onClick(DialogInterface dialog, int id) {
	    	            	  Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
	    	   	          startActivityForResult(intent, 1);
	    	              }
	    	          })
	    	          .setNegativeButton("No", new DialogInterface.OnClickListener() {
	    	              public void onClick(DialogInterface dialog, int id) {
	    	            	  EnableLocationActivity.this.finish();
	    	              }
	    	          }).show();
	    	   
	    	   
	       }

	   }
	   
	   @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		   checkLocationProviders();
	super.onActivityResult(requestCode, resultCode, data);
	}
</pre>
<p>Explanation of above code.<br />
1. First we need to create LocationManager.<br />
LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);</p>
<p>2. using isProviderEnabled Check location providers are already enabled or not.<br />
<a href="http://i1.wp.com/blog.vimviv.com/wp-content/uploads/2011/07/device2.png"><img src="http://i1.wp.com/blog.vimviv.com/wp-content/uploads/2011/07/device2.png?resize=320%2C480" alt="location providers" title="location providers" class="aligncenter size-full wp-image-514" data-recalc-dims="1" /></a></p>
<p>3. If location providers are not enabled, ask user to enable location providers and launch location settings activity.<br />
<a href="http://i2.wp.com/blog.vimviv.com/wp-content/uploads/2011/07/device4.png"><img src="http://i2.wp.com/blog.vimviv.com/wp-content/uploads/2011/07/device4.png?resize=320%2C480" alt="Prompt user" title="Prompt user" class="aligncenter size-full wp-image-515" data-recalc-dims="1" /></a><br />
4. Using onActivityResult check user has changed location settings or not.<br />
<a href="http://i1.wp.com/blog.vimviv.com/wp-content/uploads/2011/07/device5.png"><img src="http://i1.wp.com/blog.vimviv.com/wp-content/uploads/2011/07/device5.png?resize=320%2C480" alt="Activity result" title="Activity result" class="aligncenter size-full wp-image-516" data-recalc-dims="1" /></a><br />
5. Dont forget to add user permission to AndroidMenifest.xml file.</p>
<pre name="code" class="java"> 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
</pre>
<h4>Incoming search terms:</h4><ul><li><a href="http://blog.vimviv.com/android/prompt-user-enable-location-providers-android/" title="how to enable location provider in android">how to enable location provider in android</a> (19)</li><li><a href="http://blog.vimviv.com/android/prompt-user-enable-location-providers-android/" title="enable location provider">enable location provider</a> (13)</li><li><a href="http://blog.vimviv.com/android/prompt-user-enable-location-providers-android/" title="location_providers_allowed">location_providers_allowed</a> (6)</li><li><a href="http://blog.vimviv.com/android/prompt-user-enable-location-providers-android/" title="action_location_source_settings">action_location_source_settings</a> (4)</li><li><a href="http://blog.vimviv.com/android/prompt-user-enable-location-providers-android/" title="prompt user to turn on gps android">prompt user to turn on gps android</a> (3)</li><li><a href="http://blog.vimviv.com/android/prompt-user-enable-location-providers-android/" title="intent intent =new intent(settings action_location_source_sett">intent intent =new intent(settings action_location_source_sett</a> (2)</li><li><a href="http://blog.vimviv.com/android/prompt-user-enable-location-providers-android/" title="network provider android">network provider android</a> (2)</li><li><a href="http://blog.vimviv.com/android/prompt-user-enable-location-providers-android/" title="android prompt user to enable gps">android prompt user to enable gps</a> (2)</li><li><a href="http://blog.vimviv.com/android/prompt-user-enable-location-providers-android/" title="android location provider">android location provider</a> (2)</li><li><a href="http://blog.vimviv.com/android/prompt-user-enable-location-providers-android/" title="android prompt to enable gps sample">android prompt to enable gps sample</a> (2)</li></ul><div class='yarpp-related-rss'>
<p>Related posts:</p><ol>
<li><a href='http://blog.vimviv.com/blackberry/location-gps-blackberry/' rel='bookmark' title='How to get location without GPS in Blackberry'>How to get location without GPS in Blackberry</a></li>
<li><a href='http://blog.vimviv.com/android/android-some-basic-keywords/' rel='bookmark' title='Android &#8211; some basic keywords'>Android &#8211; some basic keywords</a></li>
<li><a href='http://blog.vimviv.com/android/intent-android/' rel='bookmark' title='What is Intent in android?'>What is Intent in android?</a></li>
</ol>
<img src='http://yarpp.org/pixels/29e3c972243f67e94906e1c79d9a0b70'/>
</div>
<img src="http://feeds.feedburner.com/~r/vimviv/~4/Q6hJT9sfgy0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.vimviv.com/android/prompt-user-enable-location-providers-android/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.vimviv.com/android/prompt-user-enable-location-providers-android/</feedburner:origLink></item>
		<item>
		<title>EditText in Android</title>
		<link>http://feedproxy.google.com/~r/vimviv/~3/YsMu8APdV5A/</link>
		<comments>http://blog.vimviv.com/android/edittext-android/#comments</comments>
		<pubDate>Tue, 24 May 2011 15:45:12 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
				<category><![CDATA[Android]]></category>

		<guid isPermaLink="false">http://blog.vimviv.com/?p=483</guid>
		<description><![CDATA[You are developing game apps, business apps or any app you need EditText widget for taking input from users. Android EditText widget is functionally rich and customizable.I have worked on many platforms and i have noticed that on most of the platforms you have do lots of coding for UI customization. But in android you [...]<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href='http://blog.vimviv.com/blackberry/blackberry-application-code-signing/' rel='bookmark' title='Blackberry application signing'>Blackberry application signing</a></li>
<li><a href='http://blog.vimviv.com/android/started-android/' rel='bookmark' title='Getting Started With Android'>Getting Started With Android</a></li>
</ol>
<img src='http://yarpp.org/pixels/29e3c972243f67e94906e1c79d9a0b70'/>
</div>
]]></description>
				<content:encoded><![CDATA[<p>You are developing game apps, business apps or any app you need EditText widget for taking input from users. Android EditText widget is functionally rich and customizable.I have worked on many platforms and i have noticed that on most of the platforms you have do lots of coding for UI customization. But in android you can easily customize UI elements as per your requirements. In this post i am trying to collect most of the information about android EditText. EditText is the subclass of TextView class.<br />
Like other widgets you can add a simple EditText </p>
<p><span id="more-483"></span><br />
using java code</p>
<pre name="code" class="java">
EditText editText = new EditText(context);
</pre>
<p>or using XML</p>
<pre name="code" class="xml">
<EditText 
    android:layout_height="wrap_content" 
    android:layout_width="match_parent" 
    android:id="@+id/editText1"></EditText>
</pre>
<p><strong>Single-line EditText:</strong></p>
<p>Single-line EditText means if you press &#8220;enter key&#8221; on EditText,focus will go to the next widget. Default behavior of EditText is multi-line.It means if you press &#8220;enter key&#8221;, a new line will add to the EditText.<br />
using android:singleLine=&#8221;true&#8221; property you can make single-line EditText. But this property is now deprecated.<br />
So if you add any inputtype property, EditText will become single-line EditText.<br />
e.g. android:inputType=&#8221;text&#8221;</p>
<p><strong>Multi-line EditText:</strong><br />
There are two properties are available for multi-line Edittext.<br />
<strong>a. android:lines: </strong><br />
Using &#8220;lines&#8221; property you can specify height of edittext in terms of lines.<br />
e.g. android:lines = &#8220;3&#8243; means only 3 lines will be visible in EditText and for 4rth line, you have to scroll vertically.<br />
<div id="attachment_485" class="wp-caption aligncenter" style="width: 421px"><a href="http://i2.wp.com/blog.vimviv.com/wp-content/uploads/2011/05/lines1.jpg"><img src="http://i2.wp.com/blog.vimviv.com/wp-content/uploads/2011/05/lines1.jpg?resize=411%2C130" alt="android:lines" title="lines" class="size-full wp-image-485" data-recalc-dims="1" /></a><p class="wp-caption-text">android:lines</p></div></p>
<p><strong>android:inputType</strong><br />
Using the inputType property we can restrict use to enter the correct data.<br />
e.g.</p>
<pre name="code" class="xml">
<EditText 
    android:layout_height="wrap_content" 
    android:layout_width="fill_parent" 
    android:id="@+id/editText1" 
    android:inputType="number"></EditText>
</pre>
<p><strong>b.android:maxLines</strong><br />
In the above example user can enter only numbers in the EditText widget. If you specify a inputType, EditText will become single line.<br />
using maxLines property you can specify the maximum height of the EditText.<br />
e.g.android:maxLines=&#8221;3&#8243; means first only single line will be visible and when you press &#8220;enter key&#8221;, EditText&#8217;s height will expend till the maxLines.</p>
<div id="attachment_486" class="wp-caption aligncenter" style="width: 417px"><a href="http://i1.wp.com/blog.vimviv.com/wp-content/uploads/2011/05/maxline.jpg"><img src="http://i1.wp.com/blog.vimviv.com/wp-content/uploads/2011/05/maxline.jpg?resize=407%2C78" alt="android:maxline" title="maxline" class="size-full wp-image-486" data-recalc-dims="1" /></a><p class="wp-caption-text">android:maxLines</p></div>
<div id="attachment_487" class="wp-caption aligncenter" style="width: 424px"><a href="http://i1.wp.com/blog.vimviv.com/wp-content/uploads/2011/05/maxline-1.jpg"><img src="http://i1.wp.com/blog.vimviv.com/wp-content/uploads/2011/05/maxline-1.jpg?resize=414%2C97" alt="android:maxLine-1" title="maxline-1" class="size-full wp-image-487" data-recalc-dims="1" /></a><p class="wp-caption-text">android:maxLine-1</p></div>
<p><strong>Gravity:</strong><br />
<div id="attachment_488" class="wp-caption aligncenter" style="width: 414px"><a href="http://i0.wp.com/blog.vimviv.com/wp-content/uploads/2011/05/gravity.jpg"><img src="http://i0.wp.com/blog.vimviv.com/wp-content/uploads/2011/05/gravity.jpg?resize=404%2C125" alt="gravity" title="gravity" class="size-full wp-image-488" data-recalc-dims="1" /></a><p class="wp-caption-text">gravity</p></div><br />
In the above image we can see that default alignment of cursor in EditText is vertical center. We can control alignment of cursor using &#8220;gravity&#8221; proprty.<br />
e.g. android:gravity=&#8221;top&#8221; will align cursor to the top left of the EditText.</p>
<p><strong>Read-only EditText:</strong><br />
Sometimes we need to disable EditText. For that we can use &#8220;editable&#8221; and &#8220;enabled&#8221; properties of EditText.<br />
<div id="attachment_489" class="wp-caption aligncenter" style="width: 417px"><a href="http://i0.wp.com/blog.vimviv.com/wp-content/uploads/2011/05/disable.jpg"><img src="http://i0.wp.com/blog.vimviv.com/wp-content/uploads/2011/05/disable.jpg?resize=407%2C72" alt="disable" title="disable" class="size-full wp-image-489" data-recalc-dims="1" /></a><p class="wp-caption-text">disable</p></div></p>
<pre name="code" class="xml">
<EditText 
    android:layout_height="wrap_content" 
    android:layout_width="match_parent" 
    android:id="@+id/editText1"
    android:editable="false"
    android:enabled="false"></EditText>
</pre>
<p><strong>Hint(Watermark) in EditText:</strong><br />
If you are using &#8220;hint&#8221; property of EditText, a small description of field will be visible inside field and if user clicks on EditText, it disappears and user is free to write something in it. So there is no need of label for EditText, if you are using &#8220;hint&#8221; property.<br />
<div id="attachment_490" class="wp-caption aligncenter" style="width: 420px"><a href="http://i0.wp.com/blog.vimviv.com/wp-content/uploads/2011/05/hint.jpg"><img src="http://i0.wp.com/blog.vimviv.com/wp-content/uploads/2011/05/hint.jpg?resize=410%2C72" alt="android:hint" title="hint" class="size-full wp-image-490" data-recalc-dims="1" /></a><p class="wp-caption-text">android:hint</p></div><br />
e.g.</p>
<pre name="code" class="xml">
 <EditText
                android:hint="Enter you name"
                android:id="@+id/editText"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"></EditText>
</pre>
<p>or from java code</p>
<pre name="code" class="java">
editText.setHint("Enter you name");
</pre>
<p><strong>Error popup in edittext:</strong><br />
Sometimes user entered invalid data in the EditText and you want to notify user that you have entered an invalid data. In this type of case you can use setError() method of EditText. It will show small popup of the error message.<br />
<div id="attachment_491" class="wp-caption aligncenter" style="width: 424px"><a href="http://i0.wp.com/blog.vimviv.com/wp-content/uploads/2011/05/error.jpg"><img src="http://i0.wp.com/blog.vimviv.com/wp-content/uploads/2011/05/error.jpg?resize=414%2C146" alt="setError" title="error" class="size-full wp-image-491" data-recalc-dims="1" /></a><p class="wp-caption-text">setError</p></div></p>
<pre name="code" class="java">	
editText.setError("Invalid Input");
</pre>
<p><strong>Hide soft keyboard:</strong><br />
Sometimes you want to hide soft keyboard on some action. You can do this using this code.</p>
<pre name="code" class="java">
InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindowToken(), 0);
</pre>
<p>If in an activity first focus is on EditText, soft keyboard will appear on activity launch. If you don&#8217;t want this, you can use this code.<br />
<activity android:windowSoftInputMode="stateHidden"></p>
<p><strong>Listen IME key events and enter key:</strong></p>
<pre name="code" class="java">
editText.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if(event!=null &#038;&#038; event.getAction()==KeyEvent.ACTION_DOWN){
					//Handle enter key
					return true;
				}
				if(actionId == EditorInfo.IME_ACTION_NEXT){
					//Handle IME NEXT key
					return true;
				}
				if(actionId == EditorInfo.IME_ACTION_DONE){
					//Handle IME DONE key
					return true;
				}
				return false;
			}
		});
</pre>
<p><strong>android:layout_weight</strong><br />
using layout_weight we can specify the ratio of the size of the child items in the layout.<br />
e.g.</p>
<pre name="code" class="xml">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <EditText 
    android:text="EditText" 
    android:layout_height="wrap_content" 
    android:layout_width="0dip" 
    android:id="@+id/editText1" 
    android:layout_weight="2"></EditText>
    <EditText 
    android:text="EditText" 
    android:layout_height="wrap_content" 
    android:layout_width="0dip" 
    android:id="@+id/editText2" 
    android:layout_weight="1"></EditText>
   
</LinearLayout>
</pre>
<p><div id="attachment_503" class="wp-caption aligncenter" style="width: 423px"><a href="http://i2.wp.com/blog.vimviv.com/wp-content/uploads/2011/05/weight.jpg"><img src="http://i2.wp.com/blog.vimviv.com/wp-content/uploads/2011/05/weight.jpg?resize=413%2C66" alt="layout_weight" title="weight" class="size-full wp-image-503" data-recalc-dims="1" /></a><p class="wp-caption-text">layout_weight</p></div><br />
Explanation of the above XML<br />
<strong>android:layout_weight:</strong> Using android:layout_weight we are specifying that first EditText will take 2/3 of the layout width and second EditText will take 1/3 of the layout_width;<br />
<strong>android:layout_width=&#8221;0dip&#8221;:</strong> If you give the layout_width = &#8220;wrap_content&#8221;,EditText will expend its width while you are typing in it.If you give the layout_width=&#8221;fill_parent&#8221;, first EditText will take 1/3 of the layout width and second EditText will take 2/3 of the layout width. Because of that i am giving layout_weight=&#8221;0dip&#8221;.</p>
<p><strong>Drawable:</strong><br />
Best thing about android widgets are, you can easily customize them. And for customization you no need to rush codes in the layout xml. So create a drawable xml in the drawable folder<br />
e.g.</p>
<pre name="code" class="xml">
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:endColor="#8dc73f"
        android:centerColor="#d4d4d4"
        android:startColor="#d4d4d4"/>
    <stroke
        android:width="1dp"
        color="#8dc73f" />
    <corners
        android:radius="5dp" />
    <padding
        android:left="7dp"
        android:top="7dp"
        android:right="7dp"
        android:bottom="7dp" />
</shape>
</pre>
<p><div id="attachment_505" class="wp-caption aligncenter" style="width: 425px"><a href="http://i2.wp.com/blog.vimviv.com/wp-content/uploads/2011/05/drawable.jpg"><img src="http://i2.wp.com/blog.vimviv.com/wp-content/uploads/2011/05/drawable.jpg?resize=415%2C59" alt="drawable" title="drawable" class="size-full wp-image-505" data-recalc-dims="1" /></a><p class="wp-caption-text">drawable</p></div><br />
and apply that drawable to the widgets.</p>
<pre name="code" class="xml">
<EditText 
    android:text="EditText" 
    android:layout_height="wrap_content" 
    android:layout_width="fill_parent" 
    android:id="@+id/editText1" 
    android:background="@drawable/edittext"></EditText>
</pre>
<p><strong>Selector:</strong><br />
EditText can be in different states like focused, disabled, pressed, etc. You can see in the previous example EditText will look same in all states.So if you want to give different looks to EditText for different states. you need to create selector xml.</p>
<pre name="code" class="xml">
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
     android:state_pressed="true"
     android:state_enabled="true"
        android:drawable="@drawable/edittext_focused" />
    <item
     android:state_focused="false"
     android:state_enabled="true"
        android:drawable="@drawable/edittext" />
    <item
     android:state_enabled="false"
        android:drawable="@drawable/edittext_disabled" />
</selector>
</pre>
<p>I will keep update this article because there are lots of things that we can do with EditText widget. If you want to suggest something to improve this post, your comments are always welcome here.</p>
<h4>Incoming search terms:</h4><ul><li><a href="http://blog.vimviv.com/android/edittext-android/" title="edittext android">edittext android</a> (76)</li><li><a href="http://blog.vimviv.com/android/edittext-android/" title="android edittext">android edittext</a> (75)</li><li><a href="http://blog.vimviv.com/android/edittext-android/" title="edittext no new line android">edittext no new line android</a> (63)</li><li><a href="http://blog.vimviv.com/android/edittext-android/" title="edit text in android">edit text in android</a> (63)</li><li><a href="http://blog.vimviv.com/android/edittext-android/" title="edittext in android">edittext in android</a> (56)</li><li><a href="http://blog.vimviv.com/android/edittext-android/" title="android custom edittext">android custom edittext</a> (54)</li><li><a href="http://blog.vimviv.com/android/edittext-android/" title="custom edittext android">custom edittext android</a> (43)</li><li><a href="http://blog.vimviv.com/android/edittext-android/" title="android edit default return key">android edit default return key</a> (33)</li><li><a href="http://blog.vimviv.com/android/edittext-android/" title="android edittext on top of image">android edittext on top of image</a> (24)</li><li><a href="http://blog.vimviv.com/android/edittext-android/" title="custom edittext in android">custom edittext in android</a> (23)</li></ul><div class='yarpp-related-rss'>
<p>Related posts:</p><ol>
<li><a href='http://blog.vimviv.com/blackberry/blackberry-application-code-signing/' rel='bookmark' title='Blackberry application signing'>Blackberry application signing</a></li>
<li><a href='http://blog.vimviv.com/android/started-android/' rel='bookmark' title='Getting Started With Android'>Getting Started With Android</a></li>
</ol>
<img src='http://yarpp.org/pixels/29e3c972243f67e94906e1c79d9a0b70'/>
</div>
<img src="http://feeds.feedburner.com/~r/vimviv/~4/YsMu8APdV5A" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.vimviv.com/android/edittext-android/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://blog.vimviv.com/android/edittext-android/</feedburner:origLink></item>
		<item>
		<title>What is Intent in android?</title>
		<link>http://feedproxy.google.com/~r/vimviv/~3/tQvntqyhMkA/</link>
		<comments>http://blog.vimviv.com/android/intent-android/#comments</comments>
		<pubDate>Sun, 15 May 2011 13:04:06 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
				<category><![CDATA[Android]]></category>

		<guid isPermaLink="false">http://blog.vimviv.com/?p=476</guid>
		<description><![CDATA[According to google “an Intent object, is a passive data structure holding an abstract description of an operation to be performed”. intent is a very powerful concept. I have seen following advantages of intents. 1. It loosely couples your application. 2. It can activate three core components of the android applications activities, services, and broadcast [...]<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href='http://blog.vimviv.com/android/started-android/' rel='bookmark' title='Getting Started With Android'>Getting Started With Android</a></li>
<li><a href='http://blog.vimviv.com/android/android-some-basic-keywords/' rel='bookmark' title='Android &#8211; some basic keywords'>Android &#8211; some basic keywords</a></li>
</ol>
<img src='http://yarpp.org/pixels/29e3c972243f67e94906e1c79d9a0b70'/>
</div>
]]></description>
				<content:encoded><![CDATA[<p>According to google “an Intent object, is a passive data structure holding an abstract description of an operation to be performed”.<br />
intent is a very powerful concept. I have seen following advantages of intents.<br />
1. It loosely couples your application.<br />
2. It can activate three core components of the android applications activities, services, and broadcast receivers.<br />
3. Using intents you can start any other activity that is installed in the system.<br />
e.g. you can start address book application and you can get contacts from address.<br />
4. Using intents you can expose your applications activity for other applications.<br />
e.g. You can register your own “Send SMS by myApp” application for sending SMS.<br />
<span id="more-476"></span><br />
<strong>Intents are of two types.</strong><br />
<strong>Explicit Intents: </strong>explicit intents used when you know the name of activity that you want to launch.<br />
e.g. </p>
<pre name="code" class="java">
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
startActivity(intent);
</pre>
<p><strong>Implicit Intents:</strong> Instead of giving name of the intent you tell the system what you want to perform and system will find suitable activity for your task.<br />
e.g.</p>
<pre name="code" class="java">
intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.vimviv.com"));
startActivity(intent);
</pre>
<p><strong><br />
Some example of explicit intents:</strong><br />
<strong>1. Start Activity:</strong></p>
<pre name="code" class="java">
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(intent);
</pre>
<p><strong><br />
 2. Get result from activity:</strong><br />
<strong><br />
a. FirstActivity.java</strong></p>
<pre name="code" class="java">
public class FirstActivity extends Activity {
	
	Button button;
	private static final int REQUEST_CODE = 10;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout ll = new LinearLayout(this);
        button = new Button(this);
        ll.addView(button);
        setContentView(ll);
        button.setText("Call Second Activity");
        button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent i = new Intent(FirstActivity.this, SecondActivity.class);
				i.putExtra("data", "Hi from First Activity");
				// Set the request code to any code you like, you can identify the
				// callback via this code
				startActivityForResult(i, REQUEST_CODE);
				
			}
		});
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	if (resultCode == RESULT_OK &#038;&#038; requestCode == REQUEST_CODE) {
			if (data.hasExtra("result")) {
				String message = data.getExtras().getString("result");
				Toast.makeText(FirstActivity.this, message, Toast.LENGTH_SHORT).show();
			}
		}
    }
}
</pre>
<p>Explanation of above code is as below:<br />
<strong>setContentView:</strong> we have added button to linear layout and after that linear layout to activity.<br />
<strong>putExtra:</strong> using startActivity we are launching SecondActivity and with putExtra method we are sending data also.<br />
<strong>onActivityResult:</strong> When Second Activity will finish it will call the onActivityResult method of FirstActivity.</p>
<p><strong>b. SecondActivity.java</strong></p>
<pre name="code" class="java">
public class SecondActivity extends Activity{

	Button button;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		LinearLayout ll = new LinearLayout(this);
		button = new Button(this);
		ll.addView(button);
		setContentView(ll);
		button.setText("back");
		String message = getIntent().getExtras().getString("data");
		Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();

			}
		});
	}

	@Override
	public void finish() {
		Intent data = new Intent();
		data.putExtra("result", "Hi from second activity");
		setResult(RESULT_OK, data);
		super.finish();
	}
}
</pre>
<p><strong>Explanation of above code is as below:</strong><br />
<strong>getExtras:</strong> Using the getExtras method we are fetching of data sent by FirstActivity.<br />
<strong>finish() :</strong>finish method will remove SecondActivity from the display stack and send data to the FirstActivity.</p>
<p><strong>3. Start Service:</strong></p>
<pre name="code" class="java">
Intent intent=new Intent("com.vimviv.service.serviceClass");  
startService(intent);
</pre>
<p><strong>implicit intents examples:</strong></p>
<p><strong>1. make a call:</strong></p>
<pre name="code" class="java">
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(“1234567890”));
startActivity(callIntent);
</pre>
<p><strong>2. Launch google map</strong></p>
<pre name="code" class="java">
intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("geo:37.423156,-122.084917?z=19"));
startActivity(intent);
</pre>
<p><strong>3. email client:</strong></p>
<pre name="code" class="java">
final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);

emailIntent .setType("plain/text");
emailIntent .putExtra(android.content.Intent.EXTRA_EMAIL, newString[]{"yourmail@website.com"});
emailIntent .putExtra(android.content.Intent.EXTRA_SUBJECT, mySubject);

emailIntent .putExtra(android.content.Intent.EXTRA_TEXT, myBodyText);

startActivity(Intent.createChooser(intent, "Send mail));
</pre>
<p><strong>4. start SMS app:</strong></p>
<pre name="code" class="java">
Intent sendIntent = new Intent(Intent.ACTION_VIEW);        
sendIntent.setData(Uri.parse("sms:"));
sendIntent.putExtra("sms_body", x);
</pre>
<p><strong><br />
5. To start a search in the Internet:</strong></p>
<pre name="code" class="java">
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH );
intent.putExtra(SearchManager.QUERY, "Android");
startActivity(intent);
</pre>
<p>For implicit intents read my next post <a href="http://blog.vimviv.com/android/intent-filter-android/">What is intent filter in android?</a></p>
<h4>Incoming search terms:</h4><ul><li><a href="http://blog.vimviv.com/android/intent-android/" title="intent in android">intent in android</a> (359)</li><li><a href="http://blog.vimviv.com/android/intent-android/" title="what is intent in android">what is intent in android</a> (270)</li><li><a href="http://blog.vimviv.com/android/intent-android/" title="intent android">intent android</a> (158)</li><li><a href="http://blog.vimviv.com/android/intent-android/" title="intent java">intent java</a> (86)</li><li><a href="http://blog.vimviv.com/android/intent-android/" title="java intent">java intent</a> (71)</li><li><a href="http://blog.vimviv.com/android/intent-android/" title="Android intent">Android intent</a> (61)</li><li><a href="http://blog.vimviv.com/android/intent-android/" title="intents in android">intents in android</a> (41)</li><li><a href="http://blog.vimviv.com/android/intent-android/" title="intent in java">intent in java</a> (40)</li><li><a href="http://blog.vimviv.com/android/intent-android/" title="what is an intent in android">what is an intent in android</a> (20)</li><li><a href="http://blog.vimviv.com/android/intent-android/" title="android intents">android intents</a> (11)</li></ul><div class='yarpp-related-rss'>
<p>Related posts:</p><ol>
<li><a href='http://blog.vimviv.com/android/started-android/' rel='bookmark' title='Getting Started With Android'>Getting Started With Android</a></li>
<li><a href='http://blog.vimviv.com/android/android-some-basic-keywords/' rel='bookmark' title='Android &#8211; some basic keywords'>Android &#8211; some basic keywords</a></li>
</ol>
<img src='http://yarpp.org/pixels/29e3c972243f67e94906e1c79d9a0b70'/>
</div>
<img src="http://feeds.feedburner.com/~r/vimviv/~4/tQvntqyhMkA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.vimviv.com/android/intent-android/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<feedburner:origLink>http://blog.vimviv.com/android/intent-android/</feedburner:origLink></item>
	</channel>
</rss><!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Page Caching using disk: enhanced (Requested URI is rejected)

 Served from: blog.vimviv.com @ 2013-05-18 17:10:38 by W3 Total Cache -->
