Part 1: Using SocialAuth to Integrate Facebook API in Android

The integration of mobile apps and social networking sites is becoming a norm today. Modern software development practices take into account the need to sync content with sites like Facebook due to their wide reach and popularity. This blog post is the first in a series of three that will explain how to integrate Facebook, LinkedIn, and Twitter in Android applications.

Although there is already an official SDK to integrate Facebook in Android applications, its implementation is quite a drawn out process and it also prevents you from integrating with other social networks.

SocialAuth Android is an easy to use open source SDK that allows integration with Facebook and provides simple code to access its various functionalities along with free support. It is one of the few SDKs available today that can help you to integrate other social networks in your Android App along with Facebook.

By using this SDK, one can easily connect with Facebook and share his/her status updates.  Users can easily view profiles, contacts, photo albums and feeds. The SDK also enables you to upload images to your Facebook profile in a breeze.

Getting Started

First you need to register your application with Facebook. Then, visit the following link to get access to API keys and secret keys: http://code.google.com/p/socialauth-android/wiki/Facebook

Integrate SDK in App

Now we can start integrating the SDK, which can be downloaded from http://code.google.com/p/socialauth-android. This SDK contains the Java libraries that hide all the intricacies of generating signatures & token and provides you with an easy mechanism to perform the rest of the calling functions. Just extract the contents and you are good to go.

  1. Copy the libs/socialauth-android-2.6.jar and libs/socialauth 4.2 jar into the libs folder of your application. If you have latest ADT, jars will be automatically added to your build path else you need to manually add the jar files in build path. We recommend you to upgrade to the latest ADT.
  2. Copy the assets/oauth_consumer.properties file to the assets folder of your application. The file is used by the SDK for the API and secret keys. Replace the default keys with the new keys that were obtained by following the step above.
  3. Add android.permission.INTERNET and android.permission.ACCESS_NETWORK_STATE in manifest.

That is all you need to get started. The SDK .zip file also contains code samples which can help you go ahead with the coding.

Implementation

You just need to click a button and it will open a Facebook login dialog box. After user authorization is completed you can get options to additional functionalities.

Facebook login dialog box

Initialization

Initialize SocialAuth Adapter Object and create a Facebook Button. On clicking the button authorize the adapter.

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
      
       adapter = new SocialAuthAdapter(new ResponseListener());
        
      facebook_button = (Button)findViewById(R.id.fb_btn);
      facebook_button.setBackgroundResource(R.drawable.facebook);
     
     facebook_button.setOnClickListener(new OnClickListener() 
     {
        public void onClick(View v) 
        {
            adapter.authorize(ProviderUI.this, Provider.FACEBOOK);
        }
    });
    }


Receive Authentication response in ResponseListener and initiate calls to get various functionalities.  See Examples below:

Update Status

Share your status by calling adapter.updateStatus() and verify response in MessageListener. You can share your status on your Facebook wall in any language.

private final class ResponseListener implements DialogListener 
{
   public void onComplete(Bundle values) {
   
      adapter.updateStatus(edit.getText().toString(), new MessageListener());                   
   }
}

// To get status of message after authentication
private final class MessageListener implements SocialAuthListener {
    @Override
    public void onExecute(Integer t) {

    Integer status = t;
    if (status.intValue() == 200 || status.intValue() == 201 ||status.intValue() == 204)
     Toast.makeText(CustomUI.this, "Message posted",Toast.LENGTH_LONG).show();
    else
    Toast.makeText(CustomUI.this, "Message not posted",Toast.LENGTH_LONG).show();
   }
}


Update Story

Share stories by calling adapter.updateStory() and verify response in MessageListener. You need the following fields to share a story: message, caption, link , imageurl.

private final class ResponseListener implements DialogListener 
{
   public void onComplete(Bundle values) {
   
     adapter.updateStory(  "Hello SocialAuth Android" ,  "Google SDK for Android",
		     "Build great social apps and get more installs.",
		     "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated 
                                             Android apps.",  "https://www.facebook.com",               
                                            "http://carbonfreepress.gr/images/facebook.png", new MessageListener());                
   }
}

// To get status of message after authentication
private final class MessageListener implements SocialAuthListener {
    @Override
    public void onExecute(Integer t) {

    Integer status = t;
    if (status.intValue() == 200 || status.intValue() == 201 ||status.intValue() == 204)
     Toast.makeText(CustomUI.this, "Message posted",Toast.LENGTH_LONG).show();


Get Profile

Get User profile by getUserprofileAsync() method and receive response in profileDataListener. You can get

User profile ID, first name, last name, email, gender, country, language , location and profile image URL for Facebook.

private final class ResponseListener implements DialogListener 
{
   public void onComplete(Bundle values) {
   
      adapter.getUserProfileAsync(new ProfileDataListener());                   
   }
}

// To receive the profile response after authentication
private final class ProfileDataListener implements SocialAuthListener {

@Override
public void onExecute(Profile t) {

   Log.d("Custom-UI", "Receiving Data");
   Profile profileMap = t;
   Log.d("Custom-UI",  "Validate ID         = " + profileMap.getValidatedId());
   Log.d("Custom-UI",  "First Name          = " + profileMap.getFirstName());
   Log.d("Custom-UI",  "Last Name           = " + profileMap.getLastName());
   Log.d("Custom-UI",  "Email               = " + profileMap.getEmail());
   Log.d("Custom-UI",  "Gender                   = " + profileMap.getGender());
   Log.d("Custom-UI",  "Country                  = " + profileMap.getCountry());
   Log.d("Custom-UI",  "Language                 = " + profileMap.getLanguage());
   Log.d("Custom-UI",  "Location                 = " + profileMap.getLocation());
   Log.d("Custom-UI",  "Profile Image URL  = " + profileMap.getProfileImageURL());


Get Contacts

Get User contacts by getContactListAsync() method and receive response in contactDataListener. You can get first name , last name and profile URL for Facebook.

private final class ResponseListener implements DialogListener 
{
   public void onComplete(Bundle values) {
   
      adapter.getContactListAsync(new ContactDataListener());                   
   }
}

// To receive the contacts response after authentication
private final class ContactDataListener implements SocialAuthListener> {

@Override
public void onExecute(List t) {

   Log.d("Custom-UI", "Receiving Data");
   List contactsList = t;
  if (contactsList != null && contactsList.size() > 0) {
  for (Contact c : contactsList) {
    Log.d("Custom-UI", "Contact ID = " + c.getId());
    Log.d("Custom-UI", "First Name = " + c.getFirstName());
    Log.d("Custom-UI", "Last Name = " + c.getLastName());
    }
}


Get User Feeds

Get User feeds by getFeedListAsync() method and receive response in feedDataListener. You can get

screen name, message , date of creation and name of user who posted the feed.

private final class ResponseListener implements DialogListener 
{
   public void onComplete(Bundle values) {
   
     adapter.getFeedsAsync(new FeedDataListener());             
   }
}

// To receive the feed response after authentication
private final class FeedDataListener implements SocialAuthListener> {

 @Override
 public void onExecute(List t) {

 Log.d("Share-Bar", "Receiving Data");
                        
 List feedList = t;
 if (feedList != null && feedList.size() > 0) {
 for (Feed f : feedList) {
     Log.d("Custom-UI ", "Feed ID = " + f.getId());
     Log.d("Custom-UI", "Screen Name = " + f.getScreenName());
     Log.d("Custom-UI", "Message = " + f.getMessage());
     Log.d("Custom-UI ", "Get From = " + f.getFrom());
     Log.d("Custom-UI ", "Created at = " + f.getCreatedAt());
     }
 }                                    
}


Get Albums

Get User albums by getAlbumsAsync() method and receive response in albumDataListener. You can get

album name, cover photo , photos count , array of images with their name and URLs.

private final class ResponseListener implements DialogListener 
{
   public void onComplete(Bundle values) {
   
     adapter.getAlbumsAsync(new AlbumDataListener());   
   }
}

// To receive the album response after authentication
private final class AlbumDataListener implements SocialAuthListener> {

@Override
public void onExecute(List t) {

  Log.d("Custom-UI", "Receiving Data");
  List albumList = t;
  if (albumList != null && albumList.size() > 0) {

  // Get Photos inside Album
  for (Album a : albumList) {
  Log.d("Custom-UI", "Album ID = " + a.getId());
  Log.d("Custom-UI", "Album Name = " + a.getName());
  Log.d("Custom-UI", "Cover Photo = " + a.getCoverPhoto());
  Log.d("Custom-UI", "Photos Count = " + a.getPhotosCount());

  photosList = a.getPhotos();
  if (photosList != null && photosList.size() > 0) {
  for (Photo p : photosList) {
        Log.d("Custom-UI", "Photo ID = " + p.getId());
        Log.d("Custom-UI", "Name     = " + p.getTitle());
        Log.d("Custom-UI", "Thumb Image = " + p.getThumbImage());
        Log.d("Custom-UI", "Small Image = " + p.getSmallImage());
        Log.d("Custom-UI", "Medium Image = " + p.getMediumImage());
        Log.d("Custom-UI", "Large Image = " + p.getLargeImage());
       }}
  }}


Upload Images

Share your images by calling adapter.uploadimageAsync() and verify response in UploadImageListener.

private final class ResponseListener implements DialogListener 
{
   public void onComplete(Bundle values) {
   
     adapter.uploadImageAsync("Landscape Images", "icon.png", bitmap, 0,new UploadImageListener());
   }
}

// To get status of image upload after authentication
private final class UploadImageListener implements SocialAuthListener {

@Override
public void onExecute(Integer t) {
  Log.d("Custom-UI", "Uploading Data");
  Integer status = t;
  Log.d("Custom-UI", String.valueOf(status));
  Toast.makeText(CustomUI.this, "Image Uploaded", Toast.LENGTH_SHORT).show();
}
}
Conclusion

That’s the overview of how to download and install SocialAuth to easily integrate Facebook with your Android applications . Our next post in this 3-post series will cover how to set up SocialAuth to integrate LinkedIn with your Android applications. To download the SocialAuth Facebook SDK, view further instructions and examples, or get support, please visit: http://code.google.com/p/socialauth-android.

Vineet Aggarwal

Vineet Aggarwal

Sr. Technical Lead

Vineet Aggarwal is a Sr. Technical Lead at 3Pillar Global Labs, which is part of 3Pillar’s company strategy in the fields of big data analytics, mobility, and cloud-based applications. Vineet leads development and support for the popular open source tool SocialAuth–Android. He also leads our Android Competency Center in India and is responsible for mentoring Android Developers across the company to develop internal expertise. He has hands-on experience with various mobile platforms and keen interest in Android and iPhone. He loves designing new apps, learning upcoming technologies, and mentoring members of the Android community.

6 Responses to “Part 1: Using SocialAuth to Integrate Facebook API in Android”
  1. Shoeb Siddique on

    Hi Vineet sir,

    Thanks for such a needy post for all developers.
    I have learn a lot from this.
    My another need is to like a facebook page using social auth.
    Is there any unblemished way to achieve that.
    Please help me.
    Thanks

    Reply
  2. Nitin Tomer on

    Hi Vineet,

    I’m beginner for android app development. I have to develop one android app using phonegap, where End user will be able to access that app through Facebook or Google+ login only. I have no idea how to do this(as I’m totally new to this)? Any help would be highly appreciable sir.

    Thanks in advance!!!

    Reply
  3. Hadi on

    If I already login on the facebook native mobile app, I don’t want to relogin via webview when calling adapter.authorize. How can I achieve that?

    Reply
  4. Himansu on

    Hi Vineet,

    Thanks for this nice blog! Its really helpful.

    I am facing one issue while trying to fetch the LinkedIn contact list. Its giving the below exception;
    ” org.brickred.socialauth.exception.ServerDataException: Failed to parse the contacts from response.http://api.linkedin.com/v1/people/~/connections:(id,first-name,last-name,public-profile-url,picture-url)

    Can you please help me out.

    Thanks in advance!

    Reply
  5. Manish Negi on

    Hi I’m trying to login using facebook via social auth but it’s showing an error :
    “URL Authentication error”

    Can anyone please help

    Reply
  6. Prinkal Kumar on

    sir,
    I have 2 questions ,Plz answer me to resolve my problem
    1. Can I use your App Id and Secret Key in my android app for the Login purpose
    2. I have Create app in facebook developer and it gives app id & secret key ….But when i use these app id &Secret key ….I have succesfully logged in but i am not able to get profile details. I got nothing from the facebook ….
    can you help…?????
    plz

    Reply
Leave a Reply
  • (will not be published)

 

Related Posts


Free product development tips delivered right to your inbox