Tuesday, April 23, 2013

Android sdk create and update and delete contact

The following permissions need to handle contacts on android application:
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" /> 

And import of 
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.RawContacts;
import android.provider.MediaStore;
are also important.
 
/* CREATE A NEW CONTACT */
String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
        ContactsContract.Contacts._ID,
        ContactsContract.Contacts.DISPLAY_NAME,
        ContactsContract.Contacts.STARRED,
        ContactsContract.Contacts.TIMES_CONTACTED,
        ContactsContract.Contacts.CONTACT_PRESENCE,
        ContactsContract.Contacts.PHOTO_ID,
        ContactsContract.Contacts.LOOKUP_KEY,
        ContactsContract.Contacts.HAS_PHONE_NUMBER,
    };
ArrayList<ContentProviderOperation> ops5 = new ArrayList<ContentProviderOperation>();
int rawContactInsertIndex = ops5.size();

Builder builder = ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI);
builder.withValue(RawContacts.ACCOUNT_TYPE, null);
builder.withValue(RawContacts.ACCOUNT_NAME, null);
ops5.add(builder.build());

// Name
builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
builder.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex);
builder.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, "Pritom"+ " " +"Kumar");
ops5.add(builder.build());

// Number
builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
builder.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex);
builder.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
builder.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, "01727499452");
builder.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_WORK);
ops5.add(builder.build());

// Picture
try
{
    Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), Uri.parse(r.getPhoto()));
    ByteArrayOutputStream image = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG , 100, image);
    builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
    builder.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex);
    builder.withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
    builder.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, image.toByteArray());
    ops.add(builder.build());
}
catch (Exception e)
{
    e.printStackTrace();
}

// Add the new contact
try
{
    getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops5);
}
catch (Exception e)
{
    e.printStackTrace();
}
String select = "(" + ContactsContract.Contacts.DISPLAY_NAME + " == \"" +Pritom+ " " +"Kumar"+ "\" )";
Cursor c = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, CONTACTS_SUMMARY_PROJECTION, select, null, ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
startManagingCursor(c);

if (c.moveToNext())
{
    System.out.println("NEW ID: "+c.getString(0));
}

/* UPDATE CONTACT BY RAW ID */
int id = 2;
String firstname = "Pritom";
String lastname = "Kumar";
String number = "01727499452";
String photo_uri = "android.resource://com.my.package/drawable/default_photo";

ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

// Name
builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI);
builder.withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=?" + " AND " + ContactsContract.Data.MIMETYPE + "=?", new String[]{String.valueOf(id), ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE});
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, lastname);
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, firstname);
ops.add(builder.build());
// Number
builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI);
builder.withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=?" + " AND " + ContactsContract.Data.MIMETYPE + "=?"+ " AND " + ContactsContract.CommonDataKinds.Organization.TYPE + "=?", new String[]{String.valueOf(id), ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE, String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_HOME)});
builder.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, number);
ops.add(builder.build());
// Picture
try
{
    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), Uri.parse(photo_uri));
    ByteArrayOutputStream image = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG , 100, image);

    builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI);
    builder.withSelection(ContactsContract.Data.CONTACT_ID + "=?" + " AND " + ContactsContract.Data.MIMETYPE + "=?", new String[]{String.valueOf(id), ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE});
    builder.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, image.toByteArray());
    ops.add(builder.build());
}
catch (Exception e)
{
    e.printStackTrace();
}
try
{
    getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
}
catch (Exception e)
{
    System.out.println(e.getMessage());
}

/* DELETE CONTACT BY RAW CONTACT ID AND CONTACT ID */
Cursor pCur = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID +" = ?", new String[]{"3"}, null);
Cursor pCur = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", new String[]{"3"}, null);
while (pCur.moveToNext())
{
    String lookupKey = pCur.getString(pCur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
    Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
    getContentResolver().delete(uri, null, null);
}

Android how to use ContactsContract to retrieve phone numbers and email addresses

ContactsContract is the contract between a contacts provider and applications 
that want to use contacts. The following code shows how to find a contact based on 
name, and once it's found, how to retrieve the various types of phone numbers and 
email addresses:
 
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.RawContacts;  
 
String NAME = "Pritom Mondal";
Cursor cursor = managedQuery(ContactsContract.Contacts.CONTENT_URI, null, "DISPLAY_NAME = '" + NAME + "'", null, null);
if (cursor.moveToFirst()) {
 String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
 Cursor phones = managedQuery(Phone.CONTENT_URI, null, Phone.CONTACT_ID + " = " + contactId, null, null);
 while (phones.moveToNext()) {
  String number = phones.getString(phones.getColumnIndex(Phone.NUMBER));
  int type = phones.getInt(phones.getColumnIndex(Phone.TYPE));
  System.out.println("TYPE: "+type+" NUMBER: "+number);
 }
 phones.close();
 
 Cursor emails = managedQuery(Email.CONTENT_URI, null, Email.CONTACT_ID + " = " + contactId, null, null);
 while (emails.moveToNext()) {
  String number = emails.getString(emails.getColumnIndex(Email.DATA));
  int type = emails.getInt(emails.getColumnIndex(Phone.TYPE));
  System.out.println("TYPE: "+type+" EMAIL: "+number);
 }
 emails.close();
}
cursor.close();

How to read android sim contacts and phone contacts separately

The <uses-permission> should be contained in the <manifest> element. See Structure of the Manifest File. So trying putting it before <application>.
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
 

try {
    	String[] PROJECTION=new String[] {Contacts._ID,
    	        Contacts.DISPLAY_NAME,
    	        Phone.NUMBER
    	    };
    	Cursor c = managedQuery(Phone.CONTENT_URI, PROJECTION, null, null, null);
    	if (c.moveToFirst()) {
    		String ClsPhonename = null;
            String ClsphoneNo = null;
            do 
            {
                ClsPhonename = c.getString(c.getColumnIndex(Contacts.DISPLAY_NAME));
                ClsphoneNo = c.getString(c.getColumnIndex(Phone.NUMBER));
                System.out.println(c.getString(c.getColumnIndex(Contacts._ID)));

                ClsphoneNo.replaceAll("\\D", "");
                ClsPhonename=ClsPhonename.replaceAll("&", "");
                ClsPhonename.replace("|","");
                String ClsPhoneName=ClsPhonename.replace("|","");
                System.out.println("Name: "+ClsPhoneName);
                System.out.println("Phone: "+ClsphoneNo);
            } while(c.moveToNext());
    	}
    	
    	
    	Uri simUri = Uri.parse("content://icc/adn"); 
        Cursor cursorSim = this.getContentResolver().query(simUri,null,null,null,null);
        String ClsSimPhonename = null; 
        String ClsSimphoneNo = null;
        while (cursorSim.moveToNext()) 
        {      
            ClsSimPhonename =cursorSim.getString(cursorSim.getColumnIndex("name"));
            ClsSimphoneNo = cursorSim.getString(cursorSim.getColumnIndex("number"));
            ClsSimphoneNo.replaceAll("\\D","");
            ClsSimphoneNo.replaceAll("&", "");
            ClsSimPhonename=ClsSimPhonename.replace("|","");
                System.out.println("SimContacts"+ClsSimPhonename);
                System.out.println("SimContactsNo"+ClsSimphoneNo);

        }
    } catch (Exception ex) {
    	System.out.println(ex.getMessage());
    	ex.printStackTrace();
    }

Create an Android Emulator SD Card and Write Data To It

Create the SD Card...

For instance, if you want to load MP3 files on a “real” Android phone, you’ll probably insert an SD card into the phone. The emulator can emulate this, but you need to jump through a few hoops:
Let's create a 64MB sd card for our Android emulator, shall we?
Linux
From a terminal...
# cd ~/android-sdk-linux/tools
# ./mksdcard 64M ~/Desktop/sdcard.iso
Windows XP
From a DOS prompt...
Actually where is your android-sdk-windows exists.
cd C:\Program Files\android-sdk-windows\tools
mksdcard 64M c:\documents and settings\tyler\desktop\sdcard.iso
Now you can use the 'Eclipse Android SDK and AVD Manager' to create a new android virtual device that can use the path to the sd card you created.

Write Data to the SD Card...

Linux
From a terminal...
# cd ~/android-sdk-linux/tools
# ./ddms
Windows XP
From a DOS prompt...
cd C:\Program Files\android-sdk-windows\tools
ddms
This will start the Dalvik Debug Monitor Server. Next...
  1. Launch your AVD with SD card from Eclipse that you created earlier
  2. From DDMS, go to 'Device -&gt; File Explorer' 
  3. Select the 'sdcard' folder
  4. Click the 'push file onto device' button
  5. Find your file and click open
That's it!
Now from inside your code you can get to the sd card's path with: Environment.getExternalStorageDirectory()

Grails get view.gsp file output to a string variable

def formValueHtml = g.include(view: "pdf/customerAndInvoiceProductDetails.gsp", model: [
      invoiceProductInstance: invoiceProductInstance,
      invoiceInstance: invoiceInstance,
      customerInstance: customerInstance
]);

Where  customerAndInvoiceProductDetails.gsp is a view file.
And  invoiceProductInstance is data object. 

Monday, April 22, 2013

Grails create criteria on model

def c = Account.createCriteria()
List results = c.list {
    like("name", "%Name Like%")
    and {
        between("amount", 500, 1000)
        eq("address", "London")
    }
    setFirstResult(0)
    setMaxResults(10)
    order("name", "desc")
    order("id", "asc")
    
    projections {
        property("id")
        groupProperty("invoice.id")
    }
}


Below is a node reference for each criterion method:

Node

Description

between
Where the property value is between to distinct values
between("balance", 500, 1000)
eq
Where a property equals a particular value
eq("branch", "London")
eqProperty
Where one property must equal another
eqProperty("lastTransaction","firstTransaction")
gt
Where a property is greater than a particular value
gt("balance",1000)
gtProperty
Where a one property must be greater than another
gtProperty("balance","overdraft")
ge
Where a property is greater than or equal to a particular value
ge("balance",1000)
geProperty
Where a one property must be greater than or equal to another
geProperty("balance","overdraft")
idEq
Where an objects id equals the specified value
idEq(1)
ilike
A case-insensitive 'like' expression
ilike("holderFirstName","Steph%")
in
Where a one property is contained within the specified list of values note: 'in' is a groovy reserve word, we must escape it by quotes.
'in'("holderAge",[18..65])
isEmpty
Where a collection property is empty
isEmpty("transactions")
isNotEmpty
Where a collection property is not empty
isNotEmpty("transactions")
isNull
Where a property is null
isNull("holderGender")
isNotNull
Where a property is not null
isNotNull("holderGender")
lt
Where a property is less than a particular value
lt("balance",1000)
ltProperty
Where a one property must be less than another
ltProperty("balance","overdraft")
le
Where a property is less than or equal to a particular value
le("balance",1000)
leProperty
Where a one property must be less than or equal to another
leProperty("balance","overdraft")
like
Equivalent to SQL like expression
like("holderFirstName","Steph%")
ne
Where a property does not equals a particular value
ne("branch", "London")
neProperty
Where one property does not equal another
neProperty("lastTransaction","firstTransaction")
order
Order the results by a particular property
order("holderLastName", "desc")
sizeEq
Where a collection property's size equals a particular value
sizeEq("transactions", 10)
sizeGt
Where a collection property's size is greater than a particular value
sizeGt("transactions", 10)
sizeGe
Where a collection property's size is greater than or equal to a particular value
sizeGe("transactions", 10)
sizeLt
Where a collection property's size is less than a particular value
sizeLt("transactions", 10)
sizeLe
Where a collection property's size is less than or equal to a particular value
sizeLe("transactions", 10)
sizeNe
Where a collection property's size is not equal to a particular value
sizeNe("transactions", 10)

With dynamic finders, you have access to options such as max, sort, etc. These are available to criteria queries as well, but they have different names:

Name Description
order(String, String)
Specifies both the sort column (the first argument) and the sort order (either 'asc' or 'desc').
order "age", "desc"
firstResult(int)
Specifies the offset for the results. A value of 0 will return all records up to the maximum specified.
firstResult 20
maxResults(int)
Specifies the maximum number of records to return.
maxResults 10
cache(boolean)
Indicates if the query should be cached (if the query cache is enabled).
cache true


Criteria also support the notion of projections. A projection is used to change the nature of the results. For example the following query uses a projection to count the number of distinct branch names that exist for each Account:


Name Description
property
Returns the given property in the returned results
property("firstName")
distinct
Returns results using a single or collection of distinct property names
distinct("fn") or distinct(['fn', 'ln'])
avg
Returns the average value of the given property
avg("age")
count
Returns the count of the given property name
count("branch")
countDistinct
Returns the count of the given property name for distinct rows
countDistinct("branch")
groupProperty
Groups the results by the given property
groupProperty("lastName")
max
Returns the maximum value of the given property
max("age")
min
Returns the minimum value of the given property
min("age")
sum
Returns the sum of the given property
sum("balance")
rowCount
Returns count of the number of rows returned
rowCount()

XXXXXXXXXXXXXXXX

Convert string to date format java SimpleDaeFormat

String string = "January 2, 2010";
Date date = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(string);
System.out.println(date); // Sat Jan 02 00:00:00 BOT 2010


DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); 

String newDateString = df.format(date);



Date and Time Pattern Result
"yyyy.MM.dd G 'at' HH:mm:ss z" 2001.07.04 AD at 12:08:56 PDT
"EEE, MMM d, ''yy" Wed, Jul 4, '01
"h:mm a" 12:08 PM
"hh 'o''clock' a, zzzz" 12 o'clock PM, Pacific Daylight Time
"K:mm a, z" 0:08 PM, PDT
"yyyyy.MMMMM.dd GGG hh:mm aaa" 02001.July.04 AD 12:08 PM
"EEE, d MMM yyyy HH:mm:ss Z" Wed, 4 Jul 2001 12:08:56 -0700
"yyMMddHHmmssZ" 010704120856-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSZ" 2001-07-04T12:08:56.235-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX" 2001-07-04T12:08:56.235-07:00
"YYYY-'W'ww-u" 2001-W27-3

Letter Date or Time Component Presentation Examples
G Era designator Text AD
y Year Year 1996; 96
Y Week year Year 2009; 09
M Month in year Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day name in week Text Tuesday; Tue
u Day number of week (1 = Monday, ..., 7 = Sunday) Number 1
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800
X Time zone ISO 8601 time zone -08; -0800; -08:00