Showing posts with label contact. Show all posts
Showing posts with label contact. Show all posts

Monday, May 6, 2013

View contact list using j2me


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package the.contact.space;

import java.util.Enumeration;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.List;
import javax.microedition.pim.Contact;
import javax.microedition.pim.ContactList;
import javax.microedition.pim.PIM;
import javax.microedition.pim.PIMList;

/**
 * @author User
 */
public class ViewContactList extends Form implements CommandListener {
    private final Home midlet;
    private Command cmdBack;
    private Enumeration contacts;
    private List contactList;
    private ContactList contList;

    /**
     *
     */
    public ViewContactList(String title, Home midlet) {
        super(title);
        this.midlet = midlet;
        cmdBack = new Command("Back", Command.BACK, 1);
        addCommand(cmdBack);
        setCommandListener(this);
        contactList = new List("Contact List", List.IMPLICIT);
        viewContactList2();
    }
    
    private void viewContactList2() {
        try {
            PIM pimInst = PIM.getInstance();
            contList = (ContactList) pimInst.openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY);
            contacts = contList.items();
            while (contacts.hasMoreElements()) {
                Contact tCont = (Contact) contacts.nextElement();
                String[] nameValues = tCont.getStringArray(Contact.NAME, 0);
                String firstName = nameValues[Contact.NAME_GIVEN];
                String lastName = nameValues[Contact.NAME_FAMILY];
                String phone = tCont.getString(Contact.TEL, 0);
                String email = null;
                try {
                    email = tCont.getString(Contact.EMAIL, 0);
                } catch (Exception ex) {}
                contactList.append(firstName + " " + lastName + "\n" + phone, null);
            }
            contactList.addCommand(cmdBack);
            contactList.setCommandListener(this);
            this.midlet.getDisplay().setCurrent(contactList);
        } catch (Exception ex) {
            ex.printStackTrace();
            Alert error = new Alert("Error", "No available contacts."+ex.getMessage(), null, AlertType.ERROR);
            error.setTimeout(Alert.FOREVER);
            this.midlet.getDisplay().setCurrent(error);
            return;
        }
    }
    
    public void commandAction(Command c, Displayable d) {
        if (c == cmdBack) {
            midlet.displayMainMIDlet();
        }
    }
}

Wednesday, April 24, 2013

Use Android’s ContentObserver in Your Code to Listen to Data Changes such as contact change.

ContentObserver make some work easier, such if you want to track by your own sdk application suppose when your contacts being changed, you can easily do that.

To use the ContentObserver you have to take two steps:
  • Implement a subclass of ContentObserver
  • Register your content observer to listen for changes 

Implement a subclass of ContentObserver

ContentObserver is an abstract class with no abstract methods. Its two onChange() methods are implemented without any logic. And since these are called whenever a change occurs, you have to override them.
Since Google added one of the two overloaded onChange() methods as recently as API-level 16, this method’s default behavior is to call the other, older method.
Here is, what a normal implementation would look like:

class MyObserver extends ContentObserver {       
   public MyObserver(Handler handler) {
      super(handler);           
   }

   @Override
   public void onChange(boolean selfChange) {
      this.onChange(selfChange, null);
   }       

   public void onChange(boolean selfChange, Uri uri) {
      System.out.println("HMM");
   }       
}

Also notice the Handler parameter in the constructor. This handler is used to deliver the onChange() method. So if you created the Handler on the UI thread, the onChange() method will be called on the UI thread as well. In this case avoid querying the ContentProvider in this method. Instead use an AsyncTask or a Loader.
If you pass a null value to the constructor, Android calls the onChange() method immediately – regardless of the current thread used. I think it’s best to always use a handler when creating the ContentObserver object.

Register your content observer to listen for changes

To register your ContentObserver subclass you simply have to call the ContentResolver's registerContentObserver() method:

getContentResolver().registerContentObserver(Phone.CONTENT_URI, true, new MyObserver(null));

It takes three parameters. The first is the URI to listen to. I cover the URI in more detail in the next section.
The second parameter indicates whether all changes to URIs that start with the given URI should trigger a method call or just changes to exactly this one URI. This can be handy for say the ContactsContract URI with its many descendants. But it can also be detrimental in that the actual change, that caused the method call, is even more obscure to you.
The third parameter is an instance of your ContentObserver implementation.

 

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);
}