Here is the simplest way to get contacts from Google Account . I consider every android developer can access contacts from android device.
Basically I am writing code in java so that both android developer and java developer can be benefited from this blog...
First thing is that you will need the jar files from gdata (libraries for fetching data from Google) and guava
..
Now create a new java project.
Add following jar files in your project.
gdata-client-1.0.jar
gdata-client-meta-1.0.jar
gdata-contacts-3.0.jar
gdata-contacts-meta-3.0.jar
gdata-core-1.0.jar
guava-18.0.jar
.
Now use this code to get email and phone numbers from gmail.
// authenticating username and password with Google.
public ContactsService authenticateId(String userid, String password) {
ContactsService contactService = null;
try {
contactService = new ContactsService("Google");
contactService.setUserCredentials(userid, password);
// this.userId = userid;
} catch (Exception e) {
System.out.println(e);
}
return contactService;
}
// fetching email and phone number from gmail.
public void fetchContacts(ContactsService myService)
throws ServiceException, IOException {
// Request the feed
URL feedUrl = new URL("https://www.google.com/m8/feeds/contacts/"
+ username + "@gmail.com/full");
Query myQuery = new Query(feedUrl);
myQuery.setMaxResults(5000); // you can fetch 5000 contacts max.... give your counts.
ContactFeed resultFeed = myService.getFeed(myQuery, ContactFeed.class);
resultFeed.getEntries().size();
// Print the results
System.out.println(resultFeed.getTitle().getPlainText()
+ "\n\n..........\n\n");
for (int i = 0; i < resultFeed.getEntries().size(); i++) {
ContactEntry entry = resultFeed.getEntries().get(i);
if (entry.hasPhoneNumbers()) {
Name name = entry.getName();
if (name.hasFullName()) {
String fullNameToDisplay = name.getFullName().getValue();
System.out.println("Name:\t" + fullNameToDisplay);
} else {
System.out.println("Name:\t (no name found)");
}
System.out.println("Email addresses:");
for (Email email : entry.getEmailAddresses()) {
System.out.print("\t\temail: " + email.getAddress());
System.out.print("\n");
}
System.out.println("Phone Numbers:");
for (PhoneNumber phone : entry.getPhoneNumbers()) {
System.out.print("\t\tphone : " + phone.getPhoneNumber());
System.out.print("\n");
}
System.out.println("\t\t\n ..........NEXT........\n");
}
}
}
// main method to call above methods and to pass username and password.
public static void main(String[] args) {
try {
GoogleDATA googleContactsAccess = new GoogleDATA();
ContactsService contactSrv = googleContactsAccess.authenticateId(
"username", "password");
googleContactsAccess.printAllContacts(contactSrv);
} catch (MalformedURLException ex) {
System.out.println(ex);
} catch (IOException ex) {
System.out.println(ex);
} catch (Exception ex) {
System.out.println(ex);
}
}
And you are done with fetching contacts from Google account.
Thank you for reading my blog.
No comments:
Post a Comment