Thursday 22 March 2012

Android Alarm Example


import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class AlarmDemoActivity extends Activity {

private PendingIntent pendingIntent;

/** Called when the activity is first created. */

@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

Button buttonStart = (Button) findViewById(R.id.startalarm);

Button buttonCancel = (Button) findViewById(R.id.cancelalarm);

buttonStart.setOnClickListener(new Button.OnClickListener() {

@Override
public void onClick(View arg0) {

Intent intent= new Intent(AlarmDemoActivity.this,MyAlarmService.class);
pendingIntent =PendingIntent.getService(AlarmDemoActivity.this,1, intent,1);

AlarmManager manager=(AlarmManager)getSystemService(Context.ALARM_SERVICE);
manager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+20000, pendingIntent);
//manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 5*1000, pendingIntent);
}
});

buttonCancel.setOnClickListener(new Button.OnClickListener() {

@Override
public void onClick(View arg0) {

AlarmManager manager=(AlarmManager)getSystemService(Context.ALARM_SERVICE);
manager.cancel(pendingIntent);
}
});

}

}



MyAlarmService.java







import android.app.Service;

import android.content.Intent;

import android.os.IBinder;

import android.widget.Toast;



public class MyAlarmService extends Service {



@Override

public void onCreate() {

// TODO Auto-generated method stub

Toast.makeText(this, "MyAlarmService.onCreate()", Toast.LENGTH_LONG).show();

}



@Override

public IBinder onBind(Intent intent) {

// TODO Auto-generated method stub

Toast.makeText(this, "MyAlarmService.onBind()", Toast.LENGTH_LONG).show();

return null;

}



@Override

public void onDestroy() {

// TODO Auto-generated method stub

super.onDestroy();

Toast.makeText(this, "MyAlarmService.onDestroy()", Toast.LENGTH_LONG).show();

}



@Override

public void onStart(Intent intent, int startId) {

// TODO Auto-generated method stub

super.onStart(intent, startId);

Toast.makeText(this, "MyAlarmService.onStart()", Toast.LENGTH_LONG).show();

}



@Override

public boolean onUnbind(Intent intent) {

// TODO Auto-generated method stub

Toast.makeText(this, "MyAlarmService.onUnbind()", Toast.LENGTH_LONG).show();

return super.onUnbind(intent);

}



}

SDcard Demo


import java.io.File;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.widget.TextView;

public class SDCardDemoActivity extends Activity {
TextView txtSpace;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        txtSpace= (TextView)findViewById(R.id.txtFreeSpace);
        txtSpace.setText("Sdcard Free Space: "+convertByte(getSdCardFreeSpace()));
        wipeMemoryCard();
    }

    public double getSdCardFreeSpace(){
    StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
    double bytesAvailable = (double)stat.getBlockSize() *(double)stat.getAvailableBlocks();
   

return bytesAvailable;
    }
   
    public String convertByte(double bytes){
    String space="\n";
    double reminder=0.0;
    if(bytes>1073741824){
    space+=((int)bytes/1073741824)+" GB,\n";
    bytes=(bytes%1073741824);
    }
    if(bytes>1048576){
    space+=((int)bytes/1048576)+" MB,\n";
    bytes=(bytes%1048576);
    }
    if(bytes>1024){
    space+=((int)bytes/1024)+" KB,\n";
    bytes=(bytes%1024);
    }
    space+=bytes+" Bytes";
    return space;
    }
    /**
     * Delete all data from sd card
     */
    public void wipeMemoryCard() {
        File deleteMatchingFile = new File(Environment
                .getExternalStorageDirectory().toString());
        try {
            File[] filenames = deleteMatchingFile.listFiles();
            if (filenames != null && filenames.length > 0) {
                for (File tempFile : filenames) {
                    if (tempFile.isDirectory()) {
                        wipeDirectory(tempFile.toString());
                        tempFile.delete();
                    } else {
                        tempFile.delete();
                    }
                }
            } else {
                deleteMatchingFile.delete();
            }
        } catch (Exception e) {
           e.printStackTrace();
        }
    }

    private static void wipeDirectory(String name) {
        File directoryFile = new File(name);
        File[] filenames = directoryFile.listFiles();
        if (filenames != null && filenames.length > 0) {
            for (File tempFile : filenames) {
                if (tempFile.isDirectory()) {
                    wipeDirectory(tempFile.toString());
                    tempFile.delete();
                } else {
                    tempFile.delete();
                }
            }
        } else {
            directoryFile.delete();
        }
    }


}

Demo Receive Call



import java.lang.reflect.Method;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import com.android.internal.telephony.ITelephony;

public class DempReceivePhone extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TelephonyManager tl = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
myPhoneListener ph = new myPhoneListener();
tl.listen(ph, PhoneStateListener.LISTEN_CALL_STATE);

}

public class myPhoneListener extends PhoneStateListener {

/*
* (non-Javadoc)
*
* @see android.telephony.PhoneStateListener#onCallStateChanged(int,
* java.lang.String)
*/
@Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
ITelephony telServices = getTeleService();
;
if (telServices != null) {
telServices.answerRingingCall();
}
Toast.makeText(getApplicationContext(), "Answer Call", 1000);

break;
case TelephonyManager.CALL_STATE_IDLE:
deleteCallLogEntry();
break;
default:
break;
}

}

}

private ITelephony getTeleService() {
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
com.android.internal.telephony.ITelephony telephonyService = null;
try {
// Java reflection to gain access to TelephonyManager's
// ITelephony getter

Class c = Class.forName(tm.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);
telephonyService = (ITelephony) m.invoke(tm);
telephonyService.endCall();
// count=telephonyService.getCallState();
Log.i("TEST",
"SHOWSCREEN: " + telephonyService.getActivePhoneType());
// telephonyService.call("9408488605");

} catch (Exception e) {
e.printStackTrace();

}
return telephonyService;
}

public void deleteCallLogEntry() {
// TODO Auto-generated method stub

String strUriCalls = "content://call_log/calls";

Uri UriCalls = Uri.parse(strUriCalls);

Cursor c = DempReceivePhone.this.getContentResolver().query(UriCalls,
null, null, null, null);

if (c.getCount() <= 0)

{

Toast.makeText(getApplicationContext(), "Call log empty",
Toast.LENGTH_SHORT).show();

}

if (c.moveToFirst()) {
//while (c.moveToNext())

{

String strNumber = fetchOutgoingNumber();

String queryString = "NUMBER='" + strNumber + "'";

Log.v("Number", queryString);

int i = DempReceivePhone.this.getContentResolver().delete(
UriCalls, queryString, null);

if (i >= 1)

{

Toast.makeText(getApplicationContext(), "Number deleted",
Toast.LENGTH_SHORT).show();

}

else

{

Toast.makeText(getApplicationContext(),
"No such number in call logs", Toast.LENGTH_SHORT)
.show();

}

}
}

}

private String fetchOutgoingNumber() {
String[] STR_FIELDS = new String[] { android.provider.CallLog.Calls.NUMBER };
Cursor cr = getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI, STR_FIELDS, null,
null, null);
cr.moveToLast();

return cr.getString(0);

}
}

android SAX parser Example


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import android.app.ListActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class XmlparseDemoActivity extends ListActivity {


ArrayList<String> item = new ArrayList<String>();

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

try {
URL rssurl = new URL("http://feeds.bbci.co.uk/news/technology/rss.xml");
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
RSSHelper rssHelper = new RSSHelper();
reader.setContentHandler(rssHelper);
System.setProperty("http.maxRedirects", "100");
InputSource input = new InputSource(rssurl.openStream());
String data=convertStreamToString(rssurl.openStream());


reader.parse(input);

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.rsslist, item);
setListAdapter(adapter);

} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXParseException sx) {

} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

/* (non-Javadoc)
* @see android.app.ListActivity#onListItemClick(android.widget.ListView, android.view.View, int, long)
*/
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse( item.get(position))));
}


class RSSHelper extends DefaultHandler {

boolean isTitle = false;

/*
* (non-Javadoc)
*
* @see org.xml.sax.helpers.DefaultHandler#characters(char[], int, int)
*/
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
System.out.println("char: "+new String(ch,start,length));
if(isTitle){
item.add(new String(ch,start,length));
Log.i("DATA",new String(ch,start,length));
}

}

/*
* (non-Javadoc)
*
* @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String,
* java.lang.String, java.lang.String)
*/
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
isTitle=false;

}

/*
* (non-Javadoc)
*
* @see
* org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String,
* java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {

System.out.println("Elements: "+localName);
if(localName.equalsIgnoreCase("title")){
isTitle=true;
}else{
isTitle=false;
}

}

}

public String convertStreamToString(InputStream is) throws IOException {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        if (is != null) {
            StringBuilder sb = new StringBuilder();
            String line;

            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
            } finally {
                is.close();
            }
            return sb.toString();
        } else {      
            return "";
        }
    }

}

Android Dom Parser Example



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import javax.xml.parsers.SAXParser;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class DemoDomParser extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       parserDom();
    }
   
    private  void parserDom(){
    URL rssurl;
try {
rssurl = new URL("http://feeds.bbci.co.uk/news/technology/rss.xml");

    Document dom = XMLfunctions.XMLfromString(convertStreamToString(rssurl.openStream()));
         Element root = dom.getDocumentElement();
         NodeList items = root.getElementsByTagName("item");
   
     
         for (int i=0;i<items.getLength();i++){
             Element item = (Element)items.item(i);
         
          Log.i("TEST","Title: "+XMLfunctions.getValue(item, "title"));
          Log.i("TEST","Description: "+XMLfunctions.getValue(item, "description"));
         
         }
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
    }
    public String convertStreamToString(InputStream is) throws IOException {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        if (is != null) {
            StringBuilder sb = new StringBuilder();
            String line;

            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
            } finally {
                is.close();
            }
            return sb.toString();
        } else {      
            return "";
        }
    }

}


XMLFunction.java






import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;


public class XMLfunctions {

public final static Document XMLfromString(String xml){

Document doc = null;

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
       
DocumentBuilder db = dbf.newDocumentBuilder();

InputSource is = new InputSource();
       is.setCharacterStream(new StringReader(xml));
       doc = db.parse(is);
     
} catch (ParserConfigurationException e) {
System.out.println("XML parse error: " + e.getMessage());
return null;
} catch (SAXException e) {
System.out.println("Wrong XML file structure: " + e.getMessage());
            return null;
} catch (IOException e) {
System.out.println("I/O exeption: " + e.getMessage());
return null;
}
     
        return doc;
       
}

/** Returns element value
 * @param elem element (it is XML tag)
 * @return Element value otherwise empty String
 */
public final static String getElementValue( Node elem ) {
    Node kid;
    if( elem != null){
        if (elem.hasChildNodes()){
            for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
                if( kid.getNodeType() == Node.TEXT_NODE  ){
                    return kid.getNodeValue();
                }
            }
        }
    }
    return "";
}


public static int numResults(Document doc){
Node results = doc.getDocumentElement();
int res = -1;

try{
res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
}catch(Exception e ){
res = -1;
}

return res;
}

public static String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return XMLfunctions.getElementValue(n.item(0));
}
}


BackUp Contact Details in android


import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerConfigurationException;

import org.xml.sax.SAXException;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.Gravity;
import android.widget.TextView;
import android.widget.Toast;

public class DemoAddressBookBackup extends Activity {

public static final String TAG = "ADDRESSBOOK BACKUP";

private ToXml toXml;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
toXml = new ToXml(Environment.getExternalStorageDirectory().toString()
+ "/test.xml");
populateContacts();

}

private void populateContacts() {
try {
toXml.initXML();

ContentResolver cr = getContentResolver();

Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);

if (cur.getCount() > 0) {

while (cur.moveToNext()) {
toXml.startContactElement();
// ID AND NAME FROM CONTACTS CONTRACTS
String id = cur.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

Log.i(TAG, "ID :" + id);
Log.i(TAG, "NAME :" + name);
toXml.createContactNameNode(name);

// GET PHONE NUMBERS WITH QUERY STRING
if (Integer
.parseInt(cur.getString(cur
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id },
null);

// WHILE WE HAVE CURSOR GET THE PHONE NUMERS
while (pCur.moveToNext()) {
// Do something with phones
String phone = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));

String phoneType = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));

Log.i(TAG, "PHONE :" + phone);
Log.i(TAG, "PHONE TYPE :" + phoneType);
toXml.createPhoneNode(phone, phoneType);
}
pCur.close();
}

// WHILE WE HAVE CURSOR GET THE EMAIL
Cursor emailCur = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID
+ " = ?", new String[] { id }, null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
String email = emailCur
.getString(emailCur
.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String emailType = emailCur
.getString(emailCur
.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));

Log.i(TAG, "EMAIL :" + email);
Log.i(TAG, "EMAIL TYPE :" + emailType);
toXml.createEmailNode(email, emailType);
}
emailCur.close();

// FOR GETTTING ZIP & POSTAL
String addrWhere = ContactsContract.Data.CONTACT_ID
+ " = ? AND " + ContactsContract.Data.MIMETYPE
+ " = ?";
String[] addrWhereParams = new String[] {
id,
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE };
Cursor addrCur = cr.query(
ContactsContract.Data.CONTENT_URI, null, addrWhere,
addrWhereParams, null);

while (addrCur.moveToNext()) {
String poBox = addrCur
.getString(addrCur
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
String street = addrCur
.getString(addrCur
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
String city = addrCur
.getString(addrCur
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
String state = addrCur
.getString(addrCur
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
String postalCode = addrCur
.getString(addrCur
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
String country = addrCur
.getString(addrCur
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
String type = addrCur
.getString(addrCur
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));

Log.i(TAG, "POBOX :" + poBox);
Log.i(TAG, "STREET :" + street);
Log.i(TAG, "CITY :" + city);
Log.i(TAG, "STATE :" + state);
Log.i(TAG, "POSTALCODE :" + postalCode);
Log.i(TAG, "COUNTRY :" + country);
Log.i(TAG, "TYPE :" + type);
if (street == null) {
street = "";
}
if (city == null) {
city = "";
}
if (state == null) {
state = "";
}
if (postalCode == null) {
postalCode = "";
}
if (country == null) {
country = "";
}
toXml.createPostalAddressNode(type, street, city,
state, postalCode, country);
}
addrCur.close();


// Get Organization details..
String noteWhere = ContactsContract.Data.CONTACT_ID
+ " = ? AND " + ContactsContract.Data.MIMETYPE
+ " = ?";
String[] noteWhereParams = new String[] {
id,
ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE };
Cursor noteCur = cr.query(
ContactsContract.Data.CONTENT_URI, null, noteWhere,
noteWhereParams, null);
if (noteCur.moveToFirst()) {
do {
String company = noteCur
.getString(noteCur
.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
Log.i(TAG, "Org :" + company);

String status = noteCur
.getString(noteCur
.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
Log.i(TAG, "Work :" + status);
toXml.createOrganizationNode(company, status);
} while (noteCur.moveToNext());

}
noteCur.close();

// Instant messanger
String imWhere = ContactsContract.Data.CONTACT_ID
+ " = ? AND " + ContactsContract.Data.MIMETYPE
+ " = ?";
String[] imWhereParams = new String[] {
id,
ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE };
Cursor imCur = cr.query(ContactsContract.Data.CONTENT_URI,
null, imWhere, imWhereParams, null);
if (imCur.moveToFirst()) {
String imName = imCur
.getString(imCur
.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA));
Log.i(TAG, "ImName :" + imName);
String imType;
imType = imCur
.getString(imCur
.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA5));
Log.i(TAG, "ImType :" + imType);
toXml.createIMNode(imName, imType);
}
imCur.close();
// Get Group Details

String groupWhere = ContactsContract.Data.CONTACT_ID
+ " = ? AND " + ContactsContract.Data.MIMETYPE
+ " = ?";
String[] groupWhereParams = new String[] {
id,
ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE };
Cursor groupCur = cr.query(
ContactsContract.Data.CONTENT_URI, null,
groupWhere, groupWhereParams, null);
if (groupCur.moveToFirst()) {
do {
String company = groupCur
.getString(groupCur
.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.DATA1));
Log.i(TAG, "Group :" + company);

String status = groupCur
.getString(groupCur
.getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID));
Log.i(TAG, "Type :" + status);

} while (groupCur.moveToNext());

}
groupCur.close();
toXml.endContactElement();
}
}
toXml.closeXML();

} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

}





ToXml.java




import java.io.BufferedReader;
import java.io.FileReader;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;

import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;


public class ToXml {

public static final String ELE_CONTACTDETAILS = "ContactDetails";
public static final String ELE_CONTACT = "Contact";
public static final String ELE_CONTACT_NAME = "ContactName";
public static final String ELE_PHONE = "Phone";
public static final String ELE_EMAIL = "Email";
public static final String ELE_POSTAL_ADDRESS = "PostalAddress";

public static final String ELE_PHONE_NO = "PhoneNo";
public static final String ELE_TYPE = "Type";

public static final String ELE_MAILID = "MailId";

public static final String ELE_STREET = "Stree";
public static final String ELE_CITY = "City";
public static final String ELE_STATE = "State";
public static final String ELE_PINCODE = "Pincode";
public static final String ELE_COUNTRY = "Country";

public static final String ELE_ORG="Orgazination";
public static final String ELE_COMPANY="Company";
public static final String ELE_STATUS="Status";

public static final String ELE_IM="IM";
public static final String ELE_IMNAME="IMName";




BufferedReader in;
StreamResult out;
TransformerHandler th;
AttributesImpl atts;

private String filePath="";
public ToXml(String path){
this.filePath=path;
out = new StreamResult(filePath);
}


public void doit() {
try {
in = new BufferedReader(new FileReader("C:\\pdf.txt"));

initXML();
String str;
/*while ((str = in.readLine()) != null) {
process(str);
}*/

startContactElement();
createContactNameNode("My Name");
createPhoneNode("90940349034", "work");
createEmailNode("abc@gmail.com", "Home");
createPostalAddressNode("Home", "street-1", "RAjkot", "gujarat", "4848374", "India");
endContactElement();
in.close();
closeXML();
} catch (Exception e) {
e.printStackTrace();
}
}

public void initXML() throws ParserConfigurationException,
TransformerConfigurationException, SAXException {
SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory
.newInstance();

th = tf.newTransformerHandler();
Transformer serializer = th.getTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
serializer.setOutputProperty(
"{http://xml.apache.org/xslt}indent-amount", "4");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
th.setResult(out);
th.startDocument();
atts = new AttributesImpl();
th.startElement("", "", ELE_CONTACTDETAILS, atts);
}





public void closeXML() throws SAXException {
th.endElement("", "", ELE_CONTACTDETAILS);
th.endDocument();
}

public void startContactElement() throws SAXException {
atts.clear();
th.startElement("", "", ELE_CONTACT, atts);
}

public void endContactElement() throws SAXException {
atts.clear();
th.endElement("", "", ELE_CONTACT);
}

public void createContactNameNode(String name) throws SAXException {
th.startElement("", "", ELE_CONTACT_NAME, atts);
th.characters(name.toCharArray(), 0, name.length());
th.endElement("", "", ELE_CONTACT_NAME);
}

public void createPhoneNode(String number, String type) throws SAXException {

th.startElement("", "", ELE_PHONE, atts);

th.startElement("", "", ELE_PHONE_NO, atts);
th.characters(number.toCharArray(), 0, number.length());
th.endElement("", "", ELE_PHONE_NO);

th.startElement("", "", ELE_TYPE, atts);
th.characters(type.toCharArray(), 0, type.length());
th.endElement("", "", ELE_TYPE);

th.endElement("", "", ELE_PHONE);

}

public void createEmailNode(String mailid, String type) throws SAXException {

th.startElement("", "", ELE_EMAIL, atts);

th.startElement("", "", ELE_MAILID, atts);
th.characters(mailid.toCharArray(), 0, mailid.length());
th.endElement("", "", ELE_MAILID);

th.startElement("", "", ELE_TYPE, atts);
th.characters(type.toCharArray(), 0, type.length());
th.endElement("", "", ELE_TYPE);

th.endElement("", "", ELE_EMAIL);

}

public void createPostalAddressNode(String type, String street,
String city, String state, String pincode, String country)
throws SAXException {

th.startElement("", "", ELE_POSTAL_ADDRESS, atts);

th.startElement("", "", ELE_TYPE, atts);
th.characters(type.toCharArray(), 0, type.length());
th.endElement("", "", ELE_TYPE);

th.startElement("", "", ELE_STREET, atts);
th.characters(street.toCharArray(), 0, street.length());
th.endElement("", "", ELE_STREET);

th.startElement("", "", ELE_CITY, atts);
th.characters(city.toCharArray(), 0, city.length());
th.endElement("", "", ELE_CITY);

th.startElement("", "", ELE_STATE, atts);
th.characters(state.toCharArray(), 0, state.length());
th.endElement("", "", ELE_STATE);

th.startElement("", "", ELE_PINCODE, atts);
th.characters(pincode.toCharArray(), 0, pincode.length());
th.endElement("", "", ELE_PINCODE);

th.startElement("", "", ELE_COUNTRY, atts);
th.characters(country.toCharArray(), 0, country.length());
th.endElement("", "", ELE_COUNTRY);

th.endElement("", "", ELE_POSTAL_ADDRESS);

}

public void createOrganizationNode(String company, String status) throws SAXException {

th.startElement("", "", ELE_ORG, atts);

th.startElement("", "", ELE_COMPANY, atts);
th.characters(company.toCharArray(), 0, company.length());
th.endElement("", "", ELE_COMPANY);

th.startElement("", "", ELE_STATUS, atts);
th.characters(status.toCharArray(), 0, status.length());
th.endElement("", "", ELE_STATUS);

th.endElement("", "", ELE_ORG);

}


public void createIMNode(String ImName, String type) throws SAXException {

th.startElement("", "", ELE_IM, atts);

th.startElement("", "", ELE_IMNAME, atts);
th.characters(ImName.toCharArray(), 0,ImName.length());
th.endElement("", "", ELE_IMNAME);

th.startElement("", "", ELE_TYPE, atts);
th.characters(type.toCharArray(), 0, type.length());
th.endElement("", "", ELE_TYPE);

th.endElement("", "", ELE_IM);

}



}


Add Contact Details in android


import java.util.ArrayList;

import android.app.Activity;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.OperationApplicationException;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.Contacts.Data;
import android.provider.ContactsContract.RawContacts;

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

/*
* Uri newPerson = addContactName();
*
* addMobilePhoneNo(newPerson); addEmail(newPerson);
* addPostalAddress(newPerson); addOrganization(newPerson);
*/

ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
int rawContactInsertIndex = ops.size();

ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
.withValue(RawContacts.ACCOUNT_TYPE, null)
.withValue(RawContacts.ACCOUNT_NAME, null).build());

//Phone Number
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID,
rawContactInsertIndex)
.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER, "9X-XXXXXXXXX")
.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.TYPE, "1").build());

//Display name/Contact name
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID,
rawContactInsertIndex)
.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.DISPLAY_NAME, "Mike Sullivan")
.build());
//Email details
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID,
rawContactInsertIndex)
.withValue(Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Email.DATA, "abc@aho.com")
.withValue(Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Email.TYPE, "2").build());


//Postal Address

ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID,
rawContactInsertIndex)
.withValue(Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE )
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.POBOX, "Postbox")

.withValue(Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE )
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, "street")

.withValue(Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE )
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, "city")

.withValue(Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE )
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.REGION, "region")

.withValue(Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE )
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, "postcode")

.withValue(Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE )
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, "country")

.withValue(Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE )
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, "3")


.build());


//Organization details
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID,
rawContactInsertIndex)
.withValue(Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE )
.withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, "Devindia")
.withValue(Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE )
.withValue(ContactsContract.CommonDataKinds.Organization.TITLE, "Developer")
.withValue(Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE )
.withValue(ContactsContract.CommonDataKinds.Organization.TYPE, "0")

.build());
//IM details
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID,
rawContactInsertIndex)
.withValue(Data.MIMETYPE, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Im.DATA, "ImName")
.withValue(Data.MIMETYPE, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE )
.withValue(ContactsContract.CommonDataKinds.Im.DATA5, "2")


.build());
try {
ContentProviderResult[] res = getContentResolver().applyBatch(
ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OperationApplicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}