Search This Blog

Friday, 30 December 2011

Working with the “ContactsContract” to query contacts in Android

Many of you are dealing with the deprecation problem of android contacts api so for that android says you to use the new ContactsContract package to avoid the issues related to the deprecation of this package.So now for that i have writen this tutorial to give you the clear view to handle the query on the contacs with this new package which was introduced in api level 5 android 2.0 and was further gets inproved in the api level 11 i.e android 3.0.
As this post is written for beginners you might want to jump directly to a specific topic within this post:

Permission
Querying a list of all available contacts
Querying basic information of a specific contact
Querying the photo of a contact
Querying all phone numbers of a contact
Querying all email addresses of a contact

Basic concept of Content Providers

Before we start let’s take a short look at the basic concept to access content providers. Content providers are providing data using a database like approach. The database of the content provider is always addressed by an unique URI e.g. “content://com.appsolut.example/exampleData”. To access a specific content provider, the first step is to create a query resulting in a Cursor which represents the returned data as an object with random access. The configuration of queries is straightforward and can be described in five steps:

Identify the unique resource identifier (URI) of the desired content provider
Generate a String array which is holding the names of the columns which you require from the database (e.g. RawContacts.CONTACT_ID). This is called projection.
If you want to filter the results using the query define a selection clause (e.g. to filter by contact ids: RawContacts.CONTACT_ID + “=?”). The ? operator acts as a parameter which is defined in the next step. This is called selection.
Create another String array for all parameters which you’ve used in your selection clause. For the above example it could be something like new String[]{contactId}. If no parameters where used just ignore this step. This array is called selectionArgs.
If you want to sort your results by table columns define a sort order like RawContacts.CONTACT_ID + ” ASC”, which will sort the results in ascending order using their contact ids. This string is called sortOrder.

Using the parameters from these five steps the query method can be called.
1 public final Cursor managedQuery(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)

Note: starting with API level 11 the managedQuery method will also be marked as deprecated but the new concept is quite similar.

Using the cursor rows can be selected and specific values of columns in this row can be returned using getters like getString or getInt.

For a more detailed description about content providers visit the documentation at http://developer.android.com/guide/topics/providers/content-providers.html – but don’t use the proposed way to access the contacts content provider as it is outdated and deprecated.
Querying contacts and further details of a contact

Enough basics, let’s query contacts and information related to these contacts. For that purpose the “android.provider.ContactsContract“ class and subpackages were introduced at API level 5.
Permission



Now we can start accessing the “ContactsContract.RawContacts” (http://developer.android.com/reference/android/provider/ContactsContract.RawContacts.html) content provider to query all available contacts stored in the smartphone. This table represents every person as a single entry (one row). In this table an unique id is assigned to each person which is stored in the RawContacts.CONTACT_ID field (column). Unlike the default _ID column this id is used in the other tables as well, so we can later use it to query additional information about this person. To get access to the RawContacts content provider we first define a projection as shown here:
1 final String[] projection = new String[] {
2 RawContacts.CONTACT_ID, // the contact id column
3 RawContacts.DELETED // column if this contact is deleted
4 };

We are interested in the contact id column and the deleted column. The deleted column is important because there can be entries in the RawContacts table which have been deleted and therefore should not be displayed anymore. With the help of the projection we can now create the Cursor using a query.
1 final Cursor rawContacts = managedQuery(
2 RawContacts.CONTENT_URI, // the URI for raw contact provider
3 projection
4 null, // selection = null, retrieve all entries
5 null, // selection is without parameters
6 null); // do not order

Using this cursor we can iterate through all available contact ids. To do so we need to identify the index of the contact id and deleted column. We can use the getColumnIndex of the cursor object to get this index.
11 final int contactIdColumnIndex = rawContacts.getColumnIndex(RawContacts.CONTACT_ID);
12
13 final int deletedColumnIndex = rawContacts.getColumnIndex(RawContacts.DELETED);

To ensure that the cursor is pointing to the beginning and that there are valid entries we use the moveToFirst method, which will move the cursor to the first entry and return true if there are entries available. Now we can iterate over all entries using a while loop which checks the isAfterLast method of the cursor which will return true if the cursor is pointing to an non-existing entry.
14 if(rawContacts.moveToFirst()) {
15 while(!rawContacts.isAfterLast()) { // still a valid entry left?
16 final int contactId = rawContacts.getInt(contactIdColumnIndex);
17 final boolean deleted = (rawContacts.getInt(deletedColumnIndex) == 1);
18 if(!deleted) {
19 doSomethingWithAContactId(contactId));
20 }
21 rawContacts.moveToNext(); // move to the next entry
22 }
23 }

Finally we can close the cursor to free resources:
24 rawContacts.close();
Querying basic information of a specific contact

Using a given contact id (for example from the previous part) we can access basic information about this person in the “ContactsContract.Contacts” (http://developer.android.com/reference/android/provider/ContactsContract.Contacts.html) table. In our example we will query the name of the contact as well as the photo id which is a reference to the photo entry in the data table and can thus later be used to query the photo as a bitmap. So first we define our projection for the columns DISPLAY_NAME and PHOTO_ID.
1 final String[] projection = new String[] {
2 Contacts.DISPLAY_NAME, // the name of the contact
3 Contacts.PHOTO_ID // the id of the column in the data table for the image
4 };

Using this selection we can create a cursor pointing to that specific contact. By using the selection and selectionArgs parameter of the query method we can filter the results of the query according to the given contact id (in our case the field contactId).
05 final Cursor contact = managedQuery(
06 Contacts.CONTENT_URI,
07 projection,
08 Contacts._ID + "=?", // filter entries on the basis of the contact id
09 new String[]{String.valueOf(contactId)}, // the parameter to which the contact id column is compared to
10 null);

Now we can retrieve the desired information.
11 if(contact.moveToFirst()) {
12 final String name = contact.getString(
13 contact.getColumnIndex(Contacts.DISPLAY_NAME));
14 final String photoId = contact.getString(
15 contact.getColumnIndex(Contacts.PHOTO_ID));
16 doSomethingWithAContactName(name);
17 doSomethingWithAContactPhotoId(photoId);
18 }
19 contact.close();
Querying the photo of a contact

The contact photos are stored as binary large objects (blob) in the “ContactsContract.Data” table. In this table all kinds of data about a contact is stored so we need a given photo id to retrieve the correct entry (see Querying basic information of a specific contact). In our example we use the field photoId to represent this id. The column in which the blob is stored is defined in the “CommonDataKinds.Photo” class. Using this Photo.PHOTO column we can define our query as shown below.
1 final Cursor photo = managedQuery(
2 Data.CONTENT_URI,
3 new String[] {Photo.PHOTO}, // column for the blob
4 Data._ID + "=?", // select row by id
5 new String[]{photoId}, // filter by photoId
6 null);

If the contact has a photo linked to its entry, the cursor will return the photo blob. Using the “BitmapFactory” we can create a Bitmap using this blob.
07 if(photo.moveToFirst()) {
08 byte[] photoBlob = photo.getBlob(
09 photo.getColumnIndex(Photo.PHOTO));
10 final Bitmap photoBitmap = BitmapFactory.decodeByteArray(
11 photoBlob, 0, photoBlob.length);
12 doSomethingWithAContactPhoto(photoBitmap);
13 }
14 photo.close();
Querying all phone numbers of a contact

The phone numbers are stored in the “ContactsContract.Data” table. Every number is represented by one entry in this table. To access the columns used for phone numbers we can use the definitions in the “ContactsContract.CommonDataKinds.Phone” class. There are three different columns available: number, type and label. The type column is used to define the type of the number e.g. work, home or other. If the type other is defined the label column can be used to get the defined name of this type. In our example we will just look at the types which are defined so our projection does not contain the label column.
1 final String[] projection = new String[] {
2 Phone.NUMBER,
3 Phone.TYPE,
4 };

As an URI for the phone number entries we can use the “Phone.CONTENT_URI” URI which filters the data table according to the media type of phone numbers. Because we only want phone numbers of a specific contact we filter the results on the basis of the given contactId field.
05 final Cursor phone = managedQuery(
06 Phone.CONTENT_URI,
07 projection,
08 Data.CONTACT_ID + "=?",
09 new String[]{String.valueOf(contactId)},
10 null);

Because there can be multiple entries we use a while loop to iterate over this cursor. To get a human readable version of the phone number type we use the getTypeLabelResource method to get the resource id of the label for a specific type.
11 if(phone.moveToFirst()) {
12 final int contactNumberColumnIndex = phone.getColumnIndex(Phone.NUMBER);
13 final int contactTypeColumnIndex = phone.getColumnIndex(Phone.TYPE);
14
15 while(!phone.isAfterLast()) {
16 final String number = phone.getString(contactNumberColumnIndex);
17 final int type = phone.getInt(contactTypeColumnIndex);
18 final int typeLabelResource = Phone.getTypeLabelResource(type);
19 doSomethingWithAContactPhoneNumber(number, typeLabelResource);
20 phone.moveToNext();
21 }
22
23 }
24 phone.close();
Querying all email addresses of a contact

The email addresses of a contact are also stored in the “ContactsContract.Data” table. To retrieve the desired information we use the defined column names and URI in the “CommonDataKinds.Email” class. With API level 11 an extra field was added to this class to represent the address of the email but as this example is designed for API level 5+ we use the old field.
1 final String[] projection = new String[] {
2 Email.DATA, // use Email.ADDRESS for API-Level 11+
3 Email.TYPE
4 };

The type of the email address is implemented like the type of phone numbers and using the getTypeLabelResource method we can retrieve a human readable label resource id of the type. So now we can create our cursor to retrieve all available email addresses.
05 final Cursor email = managedQuery(
06 Email.CONTENT_URI,
07 projection,
08 Data.CONTACT_ID + "=?",
09 new String[]{String.valueOf(contactId)},
10 null);

Just like we did process the results of the phone query we can iterate over the email cursor to extract every address.
view source
print?
11 if(email.moveToFirst()) {
12 final int contactEmailColumnIndex = email.getColumnIndex(Email.DATA);
13 final int contactTypeColumnIndex = email.getColumnIndex(Email.TYPE);
14
15 while(!email.isAfterLast()) {
16 final String address = email.getString(contactEmailColumnIndex);
17 final int type = email.getInt(contactTypeColumnIndex);
18 final int typeLabelResource = Email.getTypeLabelResource(type);
19 doSomethingWithAContactEmailAddress(address, typeLabelResource);
20 email.moveToNext();
21 }
22
23 }
24 email.close();
I hope this tutorial can be beneficial for you drop any comment or query!!!!

Friday, 25 November 2011

Amazing USB a small desktop inside !!!!!!

Think powerful portable cellphones and tablets are the future of mobile computing?, how about a small usb-stick sized computing powerhouse with dual-core 1.2-GHz CPU, 802.11n Wi-Fi, Bluetooth, HDMI-out and a microSD card slot having more then enough juice to directly boot into a full-fledged desktop operating system. Codenamed "Cotton Candy" this compact computing powerhouse is already a reality.
Developed by an Norwegian company "FXI Technologies" weighing only 21 grams the tiny PC enables “Any Screen Computing” - the device lets users attach the stick to any HDMI compatible screen and boot into an desktop operating system (currently demoed using preloaded Android 2.3 but specs shows it should support other OS's soon) and let them enjoy full computing including multimedia, computing, phone etc.
Surprisingly Small USB Stick Computer With Dual Core Processor, WiFI, Bluetooth And Card Reader
Operating-system Booted From The Mini Disk
Sadly, users won’t see this as a "consumer product" anytime soon - as the company plans to sell "Cotton Candy" to developers and OEMs for now.

Tuesday, 22 November 2011

How To Download Latest Google Android OS v 2.3.5 XXJVT On Samsung Galaxy SI9000 And Flash Using Cross-platform Heimdall Flashing Tool

If you are looking for an android firmware flashing tool like ODIN for Linux or MAC, free cross-platform utility Heimdall is the answer. While Odin is a leaked internal Samsung software, Heimdall is an open-source, cross-platform tool suite to flash ROM's onto Samsung Galaxy S devices - Heimdall uses the same protocol as Odin but is easier to use and supports cross-platform operation.
Here is an step-by-step illustrated tutorial on how to flash the latest Heimdall stock firmware packages for GT-I9000 (2.3.5, XXJVT) on Samsung Galaxy S I9000.

Heimdall Flashing Tool

Heimdall Flashing Tool
  1. Download and install Heimdall for your desktop operating system (Windows, Linux or MAC).
  2. Download the Heimdall Google Android ROM v 2.3.5 XXJVT and save on your computer.
  3. Launch Heimdall and click "Browse" and select the XXJVT_Heimdall.tar.gz file downloaded in previous step, Heimdall will extract the archive.
  4. If the archive is ok, Heimdall will display the contents as below.
  5. Switch off your Samsung Galaxy S I9000 and make sure you are into the download mode (When completely turned off, press and hold the Volume Down + Home + Power buttons simultaneously and you should see a screen with a big yellow triangle and the Android robot working on construction on your phone screen), make sure Heimdall has detected the device in "Download Mode".
  6. Goto the "Flash Tab" and Click "Start" to initiate the flashing process. (Be cautious flashing may brick your device)
  7. Let the process complete and you now have a successfully flashed phone with latest Android software.

How to deal with Simple Cursor adapter

Here is the brief tutorial of using the simple cursor adapter .This adapter get binded with the list view .This is used in case when you retrieve the value from the database and you want to show the values in the list view .So suppose you fetched the data from the database like this :-

public Cursor fetchbylevel(int levels) throws SQLException {
        Cursor mCursor = database.query(true, DATABASE_TABLE, new String[] {
                KEY_SCORE , KEY_NAME, KEY_LEVEL  },
                KEY_LEVEL + "=" +levels, null, null,null,  KEY_SCORE+" DESC", null);
       
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }
Now the above method is returning the whole set of tuples in the cursor now we have to show this cursor in the database in the required manner suppose in the above I want to show the NAME and SCORE of the player in one activity. So that can be done  by binding the listview by the simple cursor adapter. For that you first have to create an xml file the file code is given below
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout01"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <LinearLayout android:id="@+id/LinearLayout02"
        android:layout_width="130px" android:layout_height="40px" android:gravity="left">
        <TextView android:text="manasp" android:id="@+id/name"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:textSize="40dp" android:textColor="#ff0000" android:typeface="serif"></TextView>
    </LinearLayout>
    <LinearLayout android:id="@+id/LinearLayout03"
        android:layout_width="80px" android:layout_height="40px"
        android:gravity="right">
        <TextView android:text="96" android:id="@+id/score"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:textSize="40dp" android:textColor="#00ff00"></TextView>
    </LinearLayout>
</LinearLayout>




So in the above we have defined the xml named as lists.xml in which we defined the layout which is to be shown in the list view binded with simple cursor adapter. Now we have to write the one line code where we have to bind the list view .

String from[]={dataadapter.KEY_NAME,dataadapter.KEY_SCORE};
            int to[]={R.id.name,R.id.score};
            adapter=new SimpleCursorAdapter(this, R.layout.lists, cs, from, to);
            lv.setAdapter(adapter);
The above code represents the  two String array one is from[] and the other is to[]. In from array we have to give the attributes to display from the database and in to we have to pass the xml id of the view which was created in the lists.xml .

IF YOU LIKE THIS POST PLEASE COMMENT ANY QUERIES REGARDING THE ABOVE POST CAN BE ASKED !!!!!!!

Friday, 18 November 2011

A big bud in android 4.0 Face Unlock feature check this out

One of the most awaited feature of Google's upcoming major "Android OS" upgrade "Ice Cream Sandwich", is the new Face Unlock feature which allows users to unlock their devices by just looking into the front-facing camera utilizing some smart "Face recognition" technology.
The question is can the "face unlock" feature be fooled using a photo, the answer is in the video below :

Monday, 14 November 2011

How to add Custom Fonts in textview

we’re going to examine the process of using custom fonts. We’ll use this font for demonstration purposes. Download it and place the TTF file in the ./assets directory (create it if it doesn’t exist yet).
We’re going to use a basic layout file with a TextView, marked with an id of “custom_font” so we can access it in our code.
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.               android:orientation="vertical"  
  4.               android:layout_width="fill_parent"  
  5.               android:layout_height="fill_parent"  
  6.         >  
  7.   
  8.     <TextView  
  9.             android:id="@+id/custom_font"  
  10.             android:layout_width="fill_parent"  
  11.             android:layout_height="wrap_content"  
  12.             android:text="This is the Chantelli Antiqua font."  
  13.             />  
  14.   
  15. </LinearLayout>  
Open your main activity file and insert this into the onCreate() method:

  1. TextView txt = (TextView) findViewById(R.id.custom_font);  
  2. Typeface font = Typeface.createFromAsset(getAssets(), "Chantelli_Antiqua.ttf");  
  3. txt.setTypeface(font);  
The Typeface class contains a static builder method createFromAsset, which takes an AssetManager as its first parameter and a path to the file in the second argument. We’re handing it the default asset manager and the name of the font file because it’s located in the root of the “assets” folder. Once we’ve got an instance of our custom typeface, all that’s left is a call to TextView’s setTypeface() method. Simple, huh? It might also be wise to organize your fonts into a subdirectory if your assets directory is packed with other files.
There are a few potential problems that custom typefaces come with, though. Ellipsizing might not work correctly if the font doesn’t have a glyph for the special ellipsis character and internationalization might not be supported, as your font would have to handle any language that users might input. You’ll also want to keep an eye on the total size of your custom fonts, as this can grow quite large if you’re using a lot of different typefaces.
Android TextView: Using a Custom Android Font

Monday, 7 November 2011

Whats There In GingerBread android 2.3

Well you all heard about this version of android actually it has now currently surpassed its predecessor android 2.2(froyo). So you may have some FAQ's related to this version of android actually I also had and that questions I am sharing with you .
What are the biggest new features in Android Gingerbread?
Google's Android Gingerbread introduces a slew of improvements to the operating system, both on the surface and under the hood. The most significant core changes -- in terms of what will directly affect users -- revolve around four main areas:
  • Faster speed. Google promises Gingerbread is its "fastest version of Android yet," thanks to its improved responsiveness and power management.
  • Better Android battery life. According to Google, Gingerbread "takes a more active role" in policing apps that unnecessarily drain your phone's battery. With Gingerbread, the system will automatically kill an application if it's using too much of your device's power while running in the background.
  • Better application management. In addition to the automated app policing system, Gingerbread introduces an expanded app settings area that lets you easily see detailed information about each app's battery usage. The updated "Manage Applications" tool, meanwhile, is basically a built-in task manager: It lets you review all of your active applications, see what types of resources each one is utilizing, and manually force-stop any program if something is wrong.
Android Gingerbread: PowerAndroid Gingerbread:
  • An updated user interface. Android's UI gets a refresh with Gingerbread. And that brings us to our next question...
What'll look different in Android Gingerbread?
Android Gingerbread isn't the massive redesign we've been hearing about -- that may still be ahead with Google's next major release, Honeycomb -- but there are a number of interface changes you'll notice right away. Among them:
  • An updated color scheme. Gingerbread introduces a "simplified visual theme" that includes a darker notification bar and black-based menus.
Android Gingerbread: UIAndroid Gingerbread: UI
  • A new keyboard. Android Gingerbread features a redesigned on-screen keyboard that's said to be faster and more intuitive. In addition to its updated form, the keyboard now supports multitouch input and a "smart" autocorrect function.
Android Gingerbread: Keyboard
  • Improved cut-and-paste. Android Gingerbread allows you to long-press on any Web page or text input field to select words and copy them to the system clipboard.
Android Gingerbread: Cut and Paste
  • Easier file management. A new integrated Downloads app lets you access and manage every file you download, whether you get it via the Internet, e-mail, or through any other program.
Android Gingerbread: Download Manager
  • Better camera management. An updated Android camera app provides access to multiple cameras for devices with front- and rear-facing lenses.
Android Gingerbread: Camera

What new technologies will Gingerbread support?
My, you're just full of good questions today. Android Gingerbread adds support for several new kinds of technology that future Android phones -- including the newly announced Google Nexus S -- will offer. Among them:
  • Near Field Communication (NFC). As first revealed by Google CEO Eric Schmidt last month, Gingerbread will offer full support for NFC. If your phone has the necessary chip (the Nexus S does), you'll be able to tap your device against special NFC sensors to exchange information and eventually even make credit card payments.
  • Internet calling. Gingerbread enables support for SIP-based Internet phone calls. Like with the NFC function, though, devices have to support it -- and in what may end up being a barrier for many of us, the carriers have to sign off on it, too.
  • Lots of sensors. Android Gingerbread can read a whole bunch of new kinds of sensors, including gyroscopes, gravity sensors, and barometers -- yes, barometers. Measuring atmospheric pressure, evidently, is something future Android apps may do.
  • Extra-large screen sizes. Gingerbread's programming tools offer support for devices with larger-than-normal displays -- in other words, tablets. While the bulk of Android's tablet optimization is expected to arrive with Honeycomb, this is certainly a step in that direction.
What about gaming -- isn't Gingerbread supposed to get better there?
Indeed, it is. As you'll see in Google's official Android 2.3 introduction video, Gingerbread has a host of new tools designed to help developers bring high-end games to the Android platform. You can read the technical specifics, if you're interested, at Google's Android Developers site.
OK -- so when will my phone get the Gingerbread upgrade?
That, my friends, is the million-dollar question. For the most current info available, click over to this link Android 2.3 upgrade list.
If you're still waiting for Froyo, be sure to check out this Android 2.2 upgrade list, too. It's always kept up-to-date with the latest Froyo info available for all devices.

SO ANY QUERIES RELATED TO THIS POST ARE HEARTILY WELCOMED !!!!!!


Friday, 4 November 2011

Shocking Fact About Akash Tablet !!!!!


Finally India government has announced the most awaited cheapest android tablet Aakash  in India. The android tablet Aakash was revealed by the Union Human Resources Development Minister Kapil Sabil.
Aakash is powered by a 366 MHz processor with additional HD video co-processor. It has 256 MB RAM and 2GB internal memory. The memory can be expanded using a memory card to 32 GB. Two USB ports are also available for this cheap tablet. The operating system of Aakash tablet is Android version  2.2.
Aakash tablet will be available at a reduced rate of Rs.1200 for students but the price of commercial version of Aakash tablet in India will be Rs.3000.

FACT:- ACTUALLY THE WORLDS CHEAPEST TABLET HAS A DRAWBACK AS IT SUPPORTS THE ANDROID MARKET BUT DUE TO LOW HARDWARE CONFIGURATION IT DOESN'T SUPPORT LATEST TABLET ANDROID 2.2 APPLICATIONS SO THIS IS A LITTLE SHOCK FOR THE GEEKS WHO WANT TO ENJOY THEIR LATEST TABLETS APPLICATIONS ON THEIR TAB

AND READERS CAN GIVE THEIR VIEWS ABOUT THIS TABLET FACT AND CAN QUERY ANYTHING REGARDING THIS POST !!!!!