5

Can any body suggest a way, how to extract contacts from google to the android app?

Thanks!

Below is my code and I'm getting runtime error at line number 57. To be specific it shows exception in AsyncTask.

package com.example.isan.contacts;

import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.MalformedURLException;
import java.net.URL;

import com.google.gdata.client.Query;
import com.google.gdata.client.Service;
import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.data.Link;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.NoLongerAvailableException;
import com.google.gdata.util.ServiceException;


public class MainActivity extends ActionBarActivity {

private URL feedUrl;
private static final String username="username";
private static final String pwd="password";
private ContactsService service;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String url = "https://www.google.com/m8/feeds/contacts/username/full";

    try {
        this.feedUrl = new URL(url);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    new GetTask().execute();
}





private class GetTask extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        service = new ContactsService("Contacts");
        try {
            service.setUserCredentials(username, pwd);
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }
        try {
            queryEntries();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

}

private void queryEntries() throws IOException, ServiceException{
    Query myQuery = new Query(feedUrl);
    myQuery.setMaxResults(50);
    myQuery.setStartIndex(1);
    myQuery.setStringCustomParameter("showdeleted", "false");
    myQuery.setStringCustomParameter("requirealldeleted", "false");
    //        myQuery.setStringCustomParameter("sortorder", "ascending");
    //        myQuery.setStringCustomParameter("orderby", "");


    try{
        ContactFeed resultFeed = (ContactFeed)this.service.query(myQuery, ContactFeed.class);
        for (ContactEntry entry : resultFeed.getEntries()) {
            printContact(entry);
        }
        System.err.println("Total: " + resultFeed.getEntries().size() + " entries found");

    }
    catch (NoLongerAvailableException ex) {
        System.err.println("Not all placehorders of deleted entries are available");
    }

}
private void printContact(ContactEntry contact) throws IOException, ServiceException{
    System.err.println("Id: " + contact.getId());
    if (contact.getTitle() != null)
        System.err.println("Contact name: " + contact.getTitle().getPlainText());
    else {
        System.err.println("Contact has no name");
    }

    System.err.println("Last updated: " + contact.getUpdated().toUiString());
    if (contact.hasDeleted()) {
        System.err.println("Deleted:");
    }

    //        ElementHelper.printContact(System.err, contact);

    Link photoLink = contact.getLink("http://schemas.google.com/contacts/2008/rel#photo", "image/*");
    if (photoLink.getEtag() != null) {
        Service.GDataRequest request = service.createLinkQueryRequest(photoLink);

        request.execute();
        InputStream in = request.getResponseStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        RandomAccessFile file = new RandomAccessFile("/tmp/" + contact.getSelfLink().getHref().substring(contact.getSelfLink().getHref().lastIndexOf('/') + 1), "rw");

        byte[] buffer = new byte[4096];
        for (int read = 0; (read = in.read(buffer)) != -1; )
            out.write(buffer, 0, read);
        file.write(out.toByteArray());
        file.close();
        in.close();
        request.end();
    }

    System.err.println("Photo link: " + photoLink.getHref());
    String photoEtag = photoLink.getEtag();
    System.err.println("  Photo ETag: " + (photoEtag != null ? photoEtag : "(No contact photo uploaded)"));

    System.err.println("Self link: " + contact.getSelfLink().getHref());
    System.err.println("Edit link: " + contact.getEditLink().getHref());
    System.err.println("ETag: " + contact.getEtag());
    System.err.println("-------------------------------------------\n");
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

Isan Sahoo
  • 384
  • 2
  • 10

2 Answers2

1

Its simple to do. You can try this code.

public static void printAllContacts(ContactsService myService)
    throws ServiceException, IOException {
  // Request the feed
  URL feedUrl = new URL("https://www.google.com/m8/feeds/contacts/liz@gmail.com/full");
  ContactFeed resultFeed = myService.getFeed(feedUrl, ContactFeed.class);
  // Print the results
  System.out.println(resultFeed.getTitle().getPlainText());
  for (int i = 0; i < resultFeed.getEntries().size(); i++) {
    ContactEntry entry = resultFeed.getEntries().get(i);
    System.out.println("\t" + entry.getTitle().getPlainText());

    System.out.println("Email addresses:");
    for (Email email : entry.getEmailAddresses()) {
      System.out.print(" " + email.getAddress());
      if (email.getRel() != null) {
        System.out.print(" rel:" + email.getRel());
      }
      if (email.getLabel() != null) {
        System.out.print(" label:" + email.getLabel());
      }
      if (email.getPrimary()) {
        System.out.print(" (primary) ");
      }
      System.out.print("\n");
    }

    System.out.println("IM addresses:");
    for (Im im : entry.getImAddresses()) {
      System.out.print(" " + im.getAddress());
      if (im.getLabel() != null) {
        System.out.print(" label:" + im.getLabel());
      }
      if (im.getRel() != null) {
        System.out.print(" rel:" + im.getRel());
      }
      if (im.getProtocol() != null) {
        System.out.print(" protocol:" + im.getProtocol());
      }
      if (im.getPrimary()) {
        System.out.print(" (primary) ");
      }
      System.out.print("\n");
    }

    System.out.println("Groups:");
    for (GroupMembershipInfo group : entry.getGroupMembershipInfos()) {
      String groupHref = group.getHref();
      System.out.println("  Id: " + groupHref);
    }

    System.out.println("Extended Properties:");
    for (ExtendedProperty property : entry.getExtendedProperties()) {
      if (property.getValue() != null) {
        System.out.println("  " + property.getName() + "(value) = " +
            property.getValue());
      } else if (property.getXmlBlob() != null) {
        System.out.println("  " + property.getName() + "(xmlBlob)= " +
            property.getXmlBlob().getBlob());
      }
    }

    String photoLink = entry.getContactPhotoLink().getHref();
    System.out.println("Photo Link: " + photoLink);

    if (photoLink.getEtag() != null) {
      System.out.println("Contact Photo's ETag: " + photoLink.getEtag());
    }

    System.out.println("Contact's ETag: " + entry.getEtag());
  }
}

Please have a look at this, for complete guide on how to use the latest Contacts API version 3.

UPDATE

You will need to import these packages.

import com.google.gdata.client.*;
import com.google.gdata.client.contacts.*;
import com.google.gdata.data.*;
import com.google.gdata.data.contacts.*;
import com.google.gdata.data.extensions.*;
import com.google.gdata.util.*;
import java.io.IOException;
import java.net.URL;
Aritra Roy
  • 15,355
  • 10
  • 73
  • 107
-1

There is no way to import your google contacts in your app

But you can access your current contacts in your app.

HassanUsman
  • 1,787
  • 1
  • 20
  • 38