Click here to Skip to main content
15,881,281 members
Articles / DevOps / Load Testing

A beginners Guide to Social Network Integration in Android Apps: Working with Twitter and Facebook

Rate me:
Please Sign up or sign in to vote.
5.00/5 (5 votes)
5 Oct 2014CPOL20 min read 44K   2.5K   16   8
A Simple Step By Step Guide to Social Network Integration In Android

Contents

1. Background

2. Android Twitter Integration

       2.1 Setting up Twitter API

       2.2 Android Application Setup for Twitter Integration

       2.3 Layout for the App

       2.4 Authentication with oAuth

       2.5 Using the Code for oAuth

       2.6 Fetching Content

       2.7 Publishing Tweet

3. Facebook Integration

       3.1 Generating Keystore in Eclipse

       3.2 Creating and Authenticating App in Facebook

       3.3 Integrating Facebook Sdk with your project

       3.4 Using the Code for Facebook SDK

                      3.4.1 Authentication 

                      3.4.2 Posting to Wall

                      3.4.3 Extracting Information from Facebook

4. The Quick Solution: Using Android's Intent

5. Conclusion

 

1. Background

 

If you are an aspiring Android app developer then one of the basic thing you should learn is social network Integration of the Apps. To tell you the fact, user just love to share their score, their edited photos, their finsing through apps socially. If you are building a "Walking App" then user would love to share the distace they covered. If you are developing a Calorie Count App then sharing how much calorie a over weight person has shed is always intutive for the user.

But the social integration is not only limited to happiness of the app user or just another feature of the app. It incredibly increases the app visibility and helps you popularize your app through social networks. In other words it's a free advertisement for the app. 

Even though there are several tutorials and "How To" about social integration in Android platform, I havn't really found any article that elaborates both Twitter and Facebook from a single interface.

In this tutorial:

1) We will learn about Twitter Integration and Fetching Tweets

2) We will learn about facebook Integration and accessing the contents of Facebooks

3) We will finally apply our Opinion Mining Technique to the content to tell the user about positivity of the contents.

 

2. Android Twitter Integration

Twitter is one of the most amazing and powerful Social Networks which has given power to people like no other tool. Customers can tweet their complains, fans can post cheering messages and good luck to their stars, people can criticize people in public offices and public lives and those concerned can know mood of the people from the tweets.  So we would learn to post tweet from our app as well as fetch the content from tweeter through our account. 

2.1 Setting up Twitter API

Twitter, like most of the social networks and popular sites encrypts the data using 128bit SSL. Therefore data exchange to and from the server is secured. Hence working with twitter needs an authentication of the app by Twitter. This authentication is bind to app developer's account..

So the first step is to create a new App and provide it necessary Permission. Open the following address:

https://dev.twitter.com/apps/new

Image 1

Figure 2.1 New App Registration in Twitter

Fill up the form with a Unique App name. Website and Callback websites should be same as your web address. One more thing to be sure of is that URL field must start with "http://" .

If you do not have a website, you can create a blogger blog in just about two mintures. Although I highly recommend that you have your own website. This is really an important requirement if you want to go serious about your app development.

Image 2

2.2 Successfull App Creation in Twitter

As you can see by fefault the app is created with Read Only Access. You need to click on modify app permission link and change the permission to Read, Write and Access direct Messages.  If your app does not post anything, you can leave it as it is. In most cases read and write permission are sufficient and it is not necesasary for the app to access direct messages. Users actually hates those apps which tries to do that. But ours is a learning app, we will go with every dish in the hotel.Image 3

Figure 2.3 : Changing App Permission

Once you have updated your permissions, it is time to obtain  your key. Click on API Keys tab and you will see the keys. (Note: Kindly do not share your API key and Secret publically for security reasons)

Image 4

Figure 2. 4 API Key Tab in Twitter App API Key generation

 

Having successfully working out the preliminary requirement, it is time to go to our Android platform and Integrate Twitter App with ANdroid.

2.2 Android Application Setup for Twitter Integration

Fortunately there is a wonderful Library for all twitter operations for java platform called Twitter 4j It can be used in virtually all java platforms like swings, applets and obviously Android. Download the library from here>> 

Create an Android Application by name SocialIntegration(Well create project by any name you fancy. As we are using SocialIntegration here in this tutorial, you might find the steds tad easier with this project name) in Eclipse and drag and drop the Twitter 4j Core library to your project's lib folder as shown in figure 2.5.

Image 5

Figure 2.5: Setting up Twitter 4j Library with Android project

Now you can go inside MainActivity.java in the import section and type import twitter4j.*  If everything is fine you will see a list of packages inside twitter4j package. 

2.3 Layout for the App

Figure 2.6 is sufficient to elaborate what we are trying to do with our app. a) We will provide a Login button which should trigger the authentication process. Once the Authentication is successfull user can publish tweet from app. He can also search for term in Twitter whose result is displayed in the ListView. 

Image 6

Figure 2.6 AppLayout for Twitter Integration

You can design the layout as all the variables ( controls) can be seen on the Right Top panel. One the other hand, you can simply use the following readymade xml layout file to quickly have your own layout. Don't forget to clean and build your project if in case you are copying the xml.

XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.integratedideas.socialintegration.MainActivity$PlaceholderFragment"
    tools:ignore="HardcodedText" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_marginTop="10dp"
        android:layout_below="@+id/edSearch" >
        
    </ListView>

    <EditText
        android:id="@+id/edPublish"
        android:layout_width="match_parent"
        android:layout_marginRight="80dp"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/btnLoginNPublish"
        android:layout_alignLeft="@+id/edSearch"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/edSearch"
        android:layout_width="match_parent"
        android:layout_marginRight="80dp"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/listView1"
        android:layout_below="@+id/edPublish"
        android:layout_marginTop="17dp"
        android:ems="10" />

    

    <TextView
        android:id="@+id/tvMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignRight="@+id/edPublish"
        android:layout_marginRight="64dp"
        android:layout_marginTop="14dp"
        android:text="TextView" />

    <Button
        android:id="@+id/btnSearch"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/listView1"
        android:layout_alignRight="@+id/btnLoginNPublish"
        android:text="Search" />

    <Button
        android:id="@+id/btnLoginNPublish"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tvMessage"
        android:layout_toRightOf="@+id/tvMessage"
        android:text="Login" />

</RelativeLayout>

We would also keep edSearch, edPublish, btnSearch Invisible till Login and will change their visibility post login. Secondly we shall Change change the Text of btnLoginNPublish from initial text "login" to "publish" once login is successfull. Butt all that through cde.

The first thing first: i.e. Authenticating the App and extracting user information.

2.4 Authentication with oAuth

For understanding how authentication works, you should first look at figure 2.7. It will clear the concept of authentication.

Image 7

Figure 2.7 Sequence Diagram of App Authentication by Twitter

Figure 2.7 is almost a generalized sequence diagram for authentication of app for any social site including Twitter and Facebook.

So let us understand what we will be doing: We will first build a URL in our main app which contains url for invoking twitter authentication parsed with ApiSecret and ApiKey we obtained as in Figure 2.4 and will start a browser activity.

That Browser page will ask user wheather he wants to Authorize the App or not, if he does, the Url is passed to Twitter server which upon successfull validation of ApiKey and ApiSecret along with UserCredential extracted through browser cookies returns an access token and access secret. If user is not already logged into to Twitter, he is prompted with user name and password and new submitted URL contains the api key, api secret, username and password. Obviously as Twitter uses SSL, entire data  will be encrypted before submission and therefore can be considered as safe enough.

Once AccessToken or Simply Token is returned from the server to Browser, it comes with a simple javascript for redirection which forces App to relead with the new data which also contains the Access token and Access secret. 

Now the app uses this token along with the user ID obtained through access token to further request tweets or for publishing option.

2.5 Using the Code for oAuth

You must already be knowing from Fetching Data From Web Section of our Android Data handling tutorial that for accessing Internet, you must provide INTERNET permission through Manifest.

So add following two lines before <application> tag of your AndroidManifest.xml

XML
<uses-permission android:name="android.permission.INTERNET"/>
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Now we also know that network related operations are not permited in the main thread. To overcome this, we need to use AsyncTask. However to keep it simple, I would hack it to allow your app to let you access the network operations by adding following lines of code into your onCreate method just after calling super.

Java
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

Let your MainActivity class implement OnClickListener. Make the button click listener to overridden onClick method. Inside onClick method call Twitter Login method using an Executor.

Java
@Override
    public void onClick(View v) 
    {
    

        Button b=(Button)v;
        if(b.getText().toString().trim().equals("Login"))
        {
        Executor exe=new Executor()
        {
            
            @Override
            public void execute(Runnable command) 
            {
                
                // TODO Auto-generated method stub
                try
                {
                   
                     
                //loginToTwitter();
                 MyTwitterLogin();
                }
                catch(Exception ex)
                {
                    Log.i("Exception:",ex.getMessage());
                    
                }
                
            }
        };
        exe.execute(null);
        }
         
        
    }

And here is MyTwitterLogin()  method.

Java
static final String TWITTER_CALLBACK_URL = "oauth://t4jSample";
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";

public void MyTwitterLogin()
     {
         try {
             twitter.setOAuthConsumer(ApiKey, ApiSecret);
             requestToken = twitter
                     .getOAuthRequestToken(TWITTER_CALLBACK_URL);
             MainActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
                     .parse(requestToken.getAuthenticationURL())));
             
             Log.i("Request Toke.....=>",requestToken.toString());
             
            // twitter.setOAuthAccessToken(requestToken.getToken());

         } 
         catch (Exception e) 
         {
             Log.i("In getting Authentication",e.getMessage());
         }

         
     }

Where ApiKey and ApiSecrets are the values you obtained from your App setup with twitter( See Figure 2.4) .The other parameters must not be changed. Observe that we are starting an Intent which ideally displays your browser with Authentication Option as shown bellow in 2.9 When Login Button is clicked as 2.8.

Image 8

Figure 2.8: Initial Screen of the App

Image 9

Figure 2.9: Authentication URL Triggered after Clicking Login Button

Also see the request token structure in Figure 2.10. This is the token based on which Twitter responds.

Image 10

Figure 2.10: Request Token Passed to URL in Figure 2.9

Once user Authenticates the App, Browser will show authentication success and at the same time will open Main Activity Once more. 

Image 11

Figure 2.11: Browser after Authentication Success

After it redirects, your App will be reloaded, but with response token in it's data. So once the app is loaded which method is called? Obviously onCreate. So in onCreate method we will add a section with if loop that triggers if MainActivity has a response token in it's data.

Java
 Uri uri = getIntent().getData();
if(uri!=null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) 
            {

                uri = getIntent().getData();

            //URL_TWITTER_OAUTH_TOKEN
       final       String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
       final       String token = uri.getQueryParameter(URL_TWITTER_OAUTH_TOKEN);

                try {
                    
                    


                    MainActivity.this.accessToken = twitter.getOAuthAccessToken(requestToken, verifier);

                    long userID = accessToken.getUserId();
                    User user = twitter.showUser(userID);
                    uname = user.getName();
                    screenName=accessToken.getScreenName();
                    
                
                   // Log.i(uname+" "+userID+" "+accessToken.getScreenName(),response.getText());
                    tvMessage.setText("Welcome "+uname+"("+screenName+")");
                    
                    btnLoginNPublish.setText("Publish");
                    edSearch.setVisibility(View.VISIBLE);
                    edPublish.setVisibility(View.VISIBLE);
                    btnSearch.setVisibility(View.VISIBLE);
                    
                    
                   }
                catch(Exception ex1)
                {
                    
                    Log.i("Fetching Access token Error",ex1.getMessage());
                }

As you can see from requestToken and verifier ( the response from twitter server) we form an accessToken. This token contains all user relevent information. We extract the information and make the other form components visible.

Image 12

Figure 2.12: Form after successfull Authentication

Other initializations are as follows.

Java
listView1=(ListView)findViewById(R.id.listView1);
 tvMessage=(TextView)findViewById(R.id.tvMessage);
 edSearch=(EditText)findViewById(R.id.edSearch);
 tvMessage.setText("Please Login ");
 btnLoginNPublish=(Button)findViewById(R.id.btnLoginNPublish);
 btnLoginNPublish.setOnClickListener(this);
 btnLoginNPublish.setText("Login");

 btnSearch=(Button)findViewById(R.id.btnSearch);
 btnSearch.setOnClickListener(this);


 edPublish=(EditText)findViewById(R.id.edPublish);


 if(twitter==null)
 twitter = new TwitterFactory().getInstance();

 edSearch.setVisibility(View.INVISIBLE);
 edPublish.setVisibility(View.INVISIBLE);
 btnSearch.setVisibility(View.INVISIBLE);

Remember these must all appear before the "if loop". Otherwise after redirection you will get NullPointerException as none of the controls would have been initialized.

 

Update:

While working with the concept, I realized that this method of oAuth has slight problem. When we try to incorporate this concept into other apps, twitter does not redirect properly. In order to avoid that problem, add following intent filter in your AndroidManifest.xml after MainActivity's intent-filter

Java
<intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="x-oauthflow-twitter" android:host="callback" />
            </intent-filter>

Now change Callback url to:

Java
static final String TWITTER_CALLBACK_URL = "x-oauthflow-twitter://callback";

This should fix the redirection issues.

2.6 Fetching Content

I have provided a simple option for searching. You can search for topics or user name and it shows all. All you have to do is pass a query string and call the search method. Search method returns a list of Status  class where each status contains the tweet, retweet count, favourite count, mentions, date-time of creation of the tweet and so on. I will use a simple String ArrayAdapter to fetch the status and allocate to the list box. You can use the concept of Complex ListView to present the information in a much pleasent way.

Java
if(b.getText().toString().trim().equals("Search"))
          {
              ArrayList<String>tweetString=new ArrayList<String>();
              try{
              Query query = new Query(edSearch.getText().toString().trim());
              List list = twitter.search(query).getTweets();
              
              for (int i=0;i<list.size();i++)
              {

                  twitter4j.Status each = (twitter4j.Status) list.get(i);
                  tweetString.add(each.getUser().getScreenName()+":" + each.getText()+" [Retweet:"+each.getRetweetCount()+", Favourites: "+ each.getFavoriteCount()+"]");
            
              }
              String [] tweets=tweetString.toArray(new String[1]);
              ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                        android.R.layout.simple_list_item_1, tweets);
            
            listView1.setAdapter(adapter);
              }catch(Exception ex)
              {
                  
              }
              
          }

Image 15

Figure 2.13: Result of Searching

2.7 Publishing Tweet

You can publish a tweet simply by calling updateStatus method and passing the string in it's simplest form.

Java
if(b.getText().toString().trim().equals("Publish"))
          {
             try{
                 StatusUpdate su=new StatusUpdate("");
                 su.
              twitter4j.Status response = twitter.updateStatus(edPublish.getText().toString());
              alert.showAlertDialog(this, "Posting Successfull", "Your Tweet is Posted In your Timeline", true);
             }catch(Exception ex)
             {
                 alert.showAlertDialog(this, "Posting Successfull", ex.getMessage(), false);
             }
          }

However if you are intending to develop a more complete Twitter App, then you should use StatusUpdate object. it provides whole lot of fields which includes an option of replying to other tweets and so on. Some important possibilities are shown in Figure 2.15.

Image 16

Figure 2.14: Successfull Status Update( Publishing Tweet)

Download SocialIntegration_TWITTER_PART.zip and play with the app. 

Having successfully walked through the twitter part, it's time to check out Facebook Integration technique.

3. Facebook Integration

Facebook integration is bit more trickey than the twitter Integration. Facebook expects a signed application to contact it for authorization. So the integration is not straight forwards. First you need to generate a keystore in Eclipse and then signed your application with that. You need to pass the signed key while registering your App with Facebook. So we will start with getting keystore from Eclipse first which it will  use to sign your app.

3.1 Generating Keystore in Eclipse

Click Windows->Preferences->Debug  as shown bellow.

Image 17

Figure 3.1 Locating Keystore location in Eclipse

Note down the path of default debug keystore. Now Open your command prompt. You need two tools to generate a key for Eclipse: 1) keytool  2) openssl

keytool is always located in jre directory of your java installation. If java's class path is added in your system then you should have an access of it from anywhere.

first type keytool in command prompt and enter. If you see "command not found", then you have to manually change to jre directory. Now when you enter keytool command you will see it's usage.

Image 18

Figure 3.2: Locating and Changing to jre directory where keytool is located.

The next tool you need is openssl. Again type the command openssl. If again your command prompt shows that command not found, then you have to download openssl software from here>>

Extract the zip file in any directory but preferably at a location you can remember for your future work.

Now type following command in command prompt.

Quote:

keytool -exportcert -alias androiddebugkey -keystore C:\Users\Rupam\.android\debug.keystore | E:\openssl-0.9.8k_WIN32\bin\openssl
 sha1 -binary | E:\openssl-0.9.8k_WIN32\bin\openssl base64

Where the bold bart is your keystore location and as figure 3.1 and the underlined E:\openssl-... part is the location of your openssl full path that you just downloaded. After typing and entering the command, it will ask you to provide a password. Give a password that you can remember. This will be helpful when you sign your app for publishing for uploading in Google Play.

Image 19

Figure 3.3 Generating Key for Eclipse

Having generated the key, let us move straight towards Creating and Authenticating app in facebook.

3.2 Creating and Authenticating App in Facebook

Open:

https://developers.facebook.com/

Select "Create New App" under Apps section.

Image 20

Figure 3.4 Selecting to create new App in Facebook

Opt for Android.

Image 21

Figure 3.5 Creating New Android App with new App ID

Complete through the steps. And you will see following screen with all the step by step guide to install the app in your Emulator as well as importing the sdk to your app.

Download the sdk from link mentioned in this page.   Facebook often changes it's Api's, access techniques and so on. Therefore I am not providing any sdk link with this tutorial. It is always wise to download the latest one from the site which will always be available at this page.

Image 22

Figure 3.6 Screen After creating new App in Facebook, guiding user with next processes

I would urge you not to import the facebook sdk to your project at this stage. We shall use only a small fraction of it and for that you do not require the samples. But if you want to go big with facebook app development you can always import the whole SDK into your Eclipse workspace and can play with the samples.

 

Scroll down in this page and you will see that the App is asking for your Android app package name and activity name. Fill them as shown bellow.

Image 23

Figure 3.7: Filling Android Project details in Facebook App

Now the key obtained through Fig 3.3 Should be given to next screen as shown bellow:

Image 24

Figure 3.8: Entering Eclipse Key to Facebook App

Mention same keyhash for release also. And select next. That should complete your required steps for facebook integration.

3.3 Integrating Facebook Sdk with your project

There are virtually two ways of doing it: Use the method suggested by Facebook. i.e. import the sdk and then work with the samples and so on. There is also a simple way:Download facebookIntegrationEssentials.zip

Unzip the folder. You can see src, libs, res folders within it. upload src/com/facebook folder to your Eclipse project's src folder. Upload the jar files in libs folder to your project's libs folder and res/drawable-xhdpi files to your project's corresponding folder as shown in following figure:

Image 25

3.9 Preparing for the Facebook Integration

Once  you successfully complete the steps, your project should look something similar to following figure:

Image 26

Figure 3.10: Post Facebook SDK Integration Project View

Clean and build your project and you are ready to work with facebook. In the next section we shall see the coding part.

3.4 Using the Code for Facebook SDK

When you go to facebook developer's dashboard and select your app, you can see the app ID as bellow:

Image 27

Figure 3.11: App ID as Seen from Facebook  Developer Dashboard

Unlike twitter we do not need to pass the app secret for interacting with facebook. This id is what will be used to initialize a Facebook class instance which should be used ultimately to post or feth data from facebook.

Java
private Facebook facebook;
private static final String APP_ID = "YOUR_APP_ID_HERE";
private static final String[] PERMISSIONS = new String[] { "publish_stream","read_stream"};

Now facebook app needs to provide list of permissions along with authentication request. If you are wondering what are suitable requests and what are the permissions readily granted to you and what other permissions you can seek, you can open online Graph API testing tool of facebook:

https://developers.facebook.com/tools/explorer/145634995501895/?method=GET&path=me%3Ffields%3Did%2Cname&version=v2.1

Now this is an awesome tool to not only test your queries but also your access tokens, fields in the query and so on. Once you open the tool, it will automatically acquire an access token for you. You can use that to frame your queries which can be put into the code.

Image 28

Figure 3.12: Working with Facebook Graph API Tool Explorer

Having acquired the primary knowledge, let us now complete the code for authentication.

3.4.1 Authentication 

Remember from our figure 2.7 that first the App would request with a request token comprising of app id ( here secret is not needed). Facebook server upon validating the token will respond with an access token. Reception of accesstoken restart the form. So we need methods to store the tokens. We can use shared preferences to store the token. Before login is triggered, we can check if there exists an access token or not, if exists we can check for it's expiry and then open the authentication dialog. For this tutorial, I have bypassed this logic so that the authentication dialog is always opened when Login button is clicked!

Java
public boolean saveCredentials(Facebook facebook) {
            Editor editor = getApplicationContext().getSharedPreferences(KEY,
                    Context.MODE_PRIVATE).edit();
            editor.putString(TOKEN, facebook.getAccessToken());
            editor.putLong(EXPIRES, facebook.getAccessExpires());
            return editor.commit();
        }

        public boolean restoreCredentials(Facebook facebook) {
            SharedPreferences sharedPreferences = getApplicationContext()
                    .getSharedPreferences(KEY, Context.MODE_PRIVATE);
            facebook.setAccessToken(sharedPreferences.getString(TOKEN, null));
            facebook.setAccessExpires(sharedPreferences.getLong(EXPIRES, 0));
            return facebook.isSessionValid();
        }

And finally the login method goes as follows

Java
public void LoginToFacebook() 
        {
            facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH,new LoginDialogListener());
        }

If can be seen that we are passing an Instance of LoginDialogListener class which is an inner class of MainActivity, which defines the actions to be taken once the authentication process is completed.

Finally we call this method from onClick to validate login the user through facebook.

3.4.2 Posting to Wall

You can post message, photos etc to your wall.

Java
public void postToWall(String msg) {
            Log.d("Tests", "Testing graph API wall post");
             try {
                    String response = facebook.request("me");
                    Bundle parameters = new Bundle();
                    parameters.putString("message", msg);
                    parameters.putString("description", "test test test");
                    response = facebook.request("me/feed", parameters, 
                            "POST");
                    Log.d("Tests", "got response: " + response);
                    if (response == null || response.equals("") || 
                            response.equals("false")|| response.contains("error")) {
                       Log.v("Error", response.toString());
                    }
             } catch(Exception e) {
                 e.printStackTrace();
             }
        }

Using me/feed  in the query you can post in your wall. You also need to pass message as extra parameter. By default the request type is "Get". But while publishing, it must be explicitly specified as "Post". You can also test the query from facebook graph api tool explorer.

If everything goes as smooth as they should, you will see successfull authentication and posting through your app.

Image 29

Figure 3,13: Authentication and Posting in Facebook Wall

3.4.3 Fetching Information from Facebook

Figure 3.12 clearly shows that result of a query is always a JSON object. Therefore you can parse the response using JSON to fetch information. I have provided some utility methods which will be usefull for you to get basic understanding of the query structure.

Java
public void fetchFacebookFriends()
        {
             try {
                    String response = facebook.request("me");
                    
                    response = facebook.request("me/friends");
                    
                    Log.d("Tests", "got response: " + response);
                    if (response == null || response.equals("") || 
                            response.equals("false")|| response.contains("error")) {
                       Log.v("Error", response.toString());
                    }
                    else
                    {
                    
                    
                       
                            JSONObject jsonObject = new JSONObject(response);
                            try {
                             JSONArray array = jsonObject.getJSONArray("data");
                             for (int i = 0; i < array.length(); i++) {
                                 JSONObject object = (JSONObject) array.get(i);
                                 Log.d( "id = "+object.get("id"),"Name = "+object.get("name"));
                                  }
                                 } 
                            catch (JSONException e) 
                               {

                                   e.printStackTrace();
                                  }
                     
                    }
             }catch(Exception ex1)
             {
                 
             }
               }
        public void fetchMyFacebookStatuses()
        {
             try {
                    String response = facebook.request("me");
                    
                    response = facebook.request("me/statuses");
                    
                    Log.d("Tests", "got response: " + response);
                    if (response == null || response.equals("") || 
                            response.equals("false")) {
                       Log.v("Error", response.toString());
                    }
                    else
                    {
                    
                    
                       
                            JSONObject jsonObject = new JSONObject(response);
                            try {
                             JSONArray array = jsonObject.getJSONArray("data");
                             for (int i = 0; i < array.length(); i++) {
                                 JSONObject object = (JSONObject) array.get(i);
                                 Log.d( "Message id = "+object.get("id"),"Message = "+object.get("message"));
                                  }
                                 } 
                            catch (Exception e) 
                               {
                                Log.i("Error in Statuses:",e.getMessage());

                                
                                   
                                  }
                     
                    }
             }catch(Exception ex1)
             {
                 Log.i("Error in Statuses:",ex1.getMessage());
             }
               }

You can first test your query in Graph API explorer first to design the fields to be passed as Json object identifiers. On the contrary you can also trace out the fields by using break points and debug option as shown in following figure.

Image 30

Figure 3.14: String response and parsing through JSON object

Image 31

Figure 3.15 Fetching User Status Updates

You can simply Use the sample project and get started with the Integration.

All the fetching and posting methods can be tested from LoginDialogListener which is an inner class of MainActivity. After the task of Authentication is successfull, you can call the methods to test. Further you can use them in your code as par your logic.

Java
class LoginDialogListener implements DialogListener {
        public void onComplete(Bundle values) {
            saveCredentials(facebook);
            showToast( "Login Successfull in Facebook");
            //fetchFacebookFriends();
            //postToWall("Another post from Eclipse...");
             fetchMyFacebookStatuses();
            //fetchFriendsFacebookStatuses();
            
        }

showToast is a method to create a simple Toast which is nothing but a pop up dialog that gets dissapeared after couple of seconds. It is a neat way of giving user some messages.

Java
private void showToast(String message)
    {
           Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT)
                   .show();
       }

Download Testing-Facebook-Integration-App.zip and test the methods.

4. The Quick Solution: Using Android's Intent

This is the easiest and most efficient method of Sharing Data across different platforms including Twitter, Facebook, Linkedin, gamil, Bluetooth and so on. This method neither requires any app authentication through the site, nor it requires any other external libraries, nor JSON. However note that this is releavent only for sharing data and data can not be fetched using this.

 So if the only thing your app does is share data ( text, images) then go ahead and use this method. So we are going to provide two menu options: One for browing an Image and the other to Share using Android's Intent.

XML
<menu xmlns:android="http://schemas.android.com/apk/res/android" 
     xmlns:app="http://schemas.android.com/apk/res-auto">
  <item android:id="@+id/menuBrowse"
android:title="Browse Photos" />
 
   <item android:id="@+id/menuShare"
android:title="Share" 
android:actionProviderClass=
                "android.widget.ShareActionProvider"/>
   
   
</menu>

Accordingly we need to write the methos in MainActivity to handle the newsly modified menu.

As  you can see that we have added a new menu item called Share where we have used ShareActionProvider widget. Hence, whenever this item is clicked, an widget will be presented after it goes to  regular menu handling part.

Now we need to handle not only our main menu but also initialize an instance of ShareActionProvider and associate with menu option item.

Java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    //getMenuInflater().inflate(R.menu.share_menu, menu);

     MenuItem item = menu.findItem(R.id.menuShare);
     ShareActionProvider myShareActionProvider = (ShareActionProvider) item.getActionProvider();

    return super.onCreateOptionsMenu(menu);
}

If user selects browse option, we will present file chooser intent, collect the Uri of selected file.

When user choses Share button, we will first convert the fileUri to absolute path by quering Media content provider. A bitmap image will be created from the file path and will be loaded to image view.

Java
Uri fileUri=null;
    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
        Intent myIntent;
        switch (item.getItemId()) 
        {
        case R.id.menuShare:
            try{
            Log.d("Ok this is pressed","In the share menu");
            myIntent = new Intent(Intent.ACTION_SEND);
            myIntent.setType("image/jpeg");   
                try{
               myIntent.putExtra(Intent.EXTRA_STREAM, fileUri);
                }catch(Exception ex)
                {
                    
                }
            
                myIntent.putExtra(Intent.EXTRA_SUBJECT, "Sharing Example: Codeproject Tutorial");
                myIntent.putExtra(Intent.EXTRA_TEXT, "Shared SocialIntegration app written by Rupam Das");
                
                startActivity(Intent.createChooser(myIntent, "Share Image"));
            }catch(Exception ex)
            {
                
            }
            break;
        
                case R.id.menuBrowse:
            try{
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"),1);
            }catch(Exception ex)
            {
                
            }

        break;
        }        
        return true;

    }

Observe carefully the section of menuShare. Observe the use of ACTION.SEND for the intent. You can pass the fileUri directly to EXTRA_STREAM field. You can add further information by using putExtra method.

Obtaining  the absolute path is required only for displaying the selected image in our image view.

Java
public String getRealPathFromURI(Uri contentUri) {
          String[] proj = { MediaStore.Images.Media.DATA };
          
          //This method was deprecated in API level 11
          //Cursor cursor = managedQuery(contentUri, proj, null, null, null);
          
          CursorLoader cursorLoader = new CursorLoader(
                    this, 
                    contentUri, proj, null, null, null);        
          Cursor cursor = cursorLoader.loadInBackground();
          
          int column_index = 
            cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
          cursor.moveToFirst();
          return cursor.getString(column_index); 
         }

Finally here is the output:

Image 32

Figure 4.1: Result of Sharing Through Intent

And when you choose an option, the subject and the description fields will be nicely aligned.

Image 33

Figure 4.2: The data after selecting a Sharing Option

Note that this option shows those sharing options which are installed in your device. For instance I do not have Facebook app installed in my device. Therefore it does not present me with Facebook option. If you Install facebook, Linkedin, all those options will appear in the share Intent view.

 

5. Conclusion

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
CEO Integrated Ideas
India India
gasshopper.iics is a group of like minded programmers and learners in codeproject. The basic objective is to keep in touch and be notified while a member contributes an article, to check out with technology and share what we know. We are the "students" of codeproject.

This group is managed by Rupam Das, an active author here. Other Notable members include Ranjan who extends his helping hands to invaluable number of authors in their articles and writes some great articles himself.

Rupam Das is mentor of Grasshopper Network,founder and CEO of Integrated Ideas Consultancy Services, a research consultancy firm in India. He has been part of projects in several technologies including Matlab, C#, Android, OpenCV, Drupal, Omnet++, legacy C, vb, gcc, NS-2, Arduino, Raspberry-PI. Off late he has made peace with the fact that he loves C# more than anything else but is still struck in legacy style of coding.
Rupam loves algorithm and prefers Image processing, Artificial Intelligence and Bio-medical Engineering over other technologies.

He is frustrated with his poor writing and "grammer" skills but happy that coding polishes these frustrations.
This is a Organisation

115 members

Comments and Discussions

 
QuestionTwitter SDK 2.3.2 Sign in Error Pin
Member 1462437915-Oct-19 21:15
Member 1462437915-Oct-19 21:15 
Questiontweets not getting fetched Pin
Rudedude_YP1-Dec-15 20:08
Rudedude_YP1-Dec-15 20:08 
GeneralMy vote of 5 Pin
PVX0072-Nov-15 7:07
PVX0072-Nov-15 7:07 
Questiontwitter issue Pin
Member 1138418218-Jan-15 15:29
Member 1138418218-Jan-15 15:29 
Questionafter login brower does not open for access token : Pin
Member 110432839-Oct-14 22:25
Member 110432839-Oct-14 22:25 
AnswerRe: after login brower does not open for access token : Pin
Grasshopper.iics9-Oct-14 23:10
Grasshopper.iics9-Oct-14 23:10 
GeneralRe: after login brower does not open for access token : Pin
Member 1104328310-Oct-14 0:09
Member 1104328310-Oct-14 0:09 
GeneralRe: after login brower does not open for access token : Pin
Grasshopper.iics10-Oct-14 0:36
Grasshopper.iics10-Oct-14 0:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.