Wednesday, 16 April 2014

[Android] How to Set Status at facebook

Note: Originally from my another new programming blog post here


We live in a social network world more than in real world. And so android applications also need to provide sharing links for the Social network Giants Facebook and Twitter. The big Question comes: HOW!!

Well, I am an android developer, and faced a similar issue when it came to share at facebook.

Here, I will be demonstrating using a third-party SDK: easyfacebook (Official site here).

Reason for using third party tool: Facebook's official SDK needs Facebook app to be installed in the phone. If it is not, it won't work. But my app requirements were to be the least dependent-on-others app. EasyFacebook SDK does not need Facebook app to be installed.

No. 2 reason can also be stated as I was not able to get how to implement Facebook's Official SDK. The tutorials I found on the internet or via stackoverflow were outdated. The basic classes that those tutorials used were deprecated in the new version. So, I was even confused on how to use it. But I will post the tutorial with the latest Facebook SDK soon. (As soon as I complete my current project update)

However, EasyFacebook though not upgraded since ages. It was last updated far back to 2011. But still, it works. N the best thing, works without any pre-requisite of Facebook app. I love being independent as possible (Indian by heart.. <3)

Steps to implementation:

1. Make Facebook Application. To connect your app to Facebook, you must have an application at Facebook. Go to developers.facebook.com, If your visiting for the first time, it may ask you to register. Register with your facebook account.

Now as seen in image: Click on Create a new app.


Now, You will get a window for creating a new app. Type in your Application name and namespace. Choose the category and click on "Create App"

Here you go! You will get a Dashboard. Just copy your APP ID. It will be used in your application.


Now, last step at Facebook application: Register your Android App details. To do that, you first need your Key Hash. To find the key hash of your working system, follow these steps:

To generate Key Hash signature you need openssl installed in your PC. You can download it from here. Open Command prompt. Run the command:

 keytool -exportcert -alias androiddebugkey -keystore "C:\Users\Ravi\.android\debug.keystore" | openssl sha1 -binary | openssl base64  


It will ask you for your a password. Give password as "android" removing quotes. If it does not, make sure the path of keystore. The path mentioned here is generally the default, However, it may vary.

You will get an output with some big code and possibly "=" in the last. Copy the key hash.

Now, moving back to your Facebook Developer Portal. Go to settings. and fill in the following as shown in figure:



Click Add Platform, Select Android. Fill in the details. as shown. N click Save Changes.

Half work over. Really? Naa... It was just 25% yet!


Now, lets come to your facebook app. Download easyfacebook SDK from this link. 2.3 is the latest while writing this blog. Although it was last updated in far back 2011. But still can't say if the developer updates it.

So, after downloading .jar file, keep it in your lib folder of your android project. Open Eclipse, Go to your project--> libs Right Click easyandroidfacebooksdk2.3.jar --> Build Path --> Add to Build Path

Now, for newbies: Keep in mind, To make a share program, you have to create a new Intent for that. So, create an activity first, Here in tutorial, I am using "Fb.java"

Here is the code for your Fb intent:


 package com.innovativejumbo.androidFb;  
 import android.app.Activity;  
 import android.os.Bundle;  
 import android.util.Log;  
 import com.easy.facebook.android.apicall.GraphApi;  
 import com.easy.facebook.android.data.User;  
 import com.easy.facebook.android.error.EasyFacebookError;  
 import com.easy.facebook.android.facebook.FBLoginManager;  
 import com.easy.facebook.android.facebook.Facebook;  
 import com.easy.facebook.android.facebook.LoginListener;  
 public class Fb extends Activity implements LoginListener {  
      private FBLoginManager fbLoginManager;  
       //Add here your own Facebook App ID  
       public final String APP_ID = "insert_your_app_id";  
       @Override  
       public void onCreate(Bundle savedInstanceState) {  
       super.onCreate(savedInstanceState);  
       connectToFacebook();  
       }  
       public void connectToFacebook(){  
       //read about Facebook Permissions here:  
       //http://developers.facebook.com/docs/reference/api/permissions/  
       String permissions[] = {  
        "publish_stream",  
        "publish_actions"  
        };  
       fbLoginManager = new FBLoginManager(this,  
        R.layout.activity_fb,   
        APP_ID,   
        permissions);  
       if(fbLoginManager.existsSavedFacebook()){  
        fbLoginManager.loadFacebook();  
       }  
       else{  
        fbLoginManager.login();  
       }  
       }  
       @Override  
       protected void onActivityResult(int requestCode, int resultCode, android.content.Intent data){  
       fbLoginManager.loginSuccess(data);  
       }  
       public void loginSuccess(Facebook facebook) {  
  final GraphApi graphApi = new GraphApi(facebook);  
            Thread myThread = new Thread(new Runnable() {  
                @Override  
                public void run() {  
                     // TODO Auto-generated method stub  
                     User user = new User();  
                      try{  
                       user = graphApi.getMyAccountInfo();  
        graphApi.setStatus("Hello World!");  
                      } catch(EasyFacebookError e){  
                            Log.d("TAG: ", e.toString());  
                           }  
                     }  
                });  
                 myThread.start();  
            fbLoginManager.displayToast("Posted to Facebook successfully");  
          //finish this intent activity after posting.  
            finish();  
       }  
       public void logoutSuccess() {  
       fbLoginManager.displayToast("Logout Success!");  
       }  
       public void loginFail() {  
       fbLoginManager.displayToast("Login Epic Failed!");  
       }  
 }  

Call this Intent whenever you want to set the status.

If the user is logged is not logged in, a window will appear to login to Facebook.

If you are using this for the first time, the application may ask your granting the request to post to Timeline. Click OK and it will be posted. Next time, it will be posted automatically as the intent is being called.

You have many more Facebook functions also to play with in this SDK. Check here and try them out as needed. However, it lacks the documentation on how and what these methods do. Still, many of the functions are clear by their names. Give a try and enjoy.