You are on page 1of 12

Integrating Facebook Platform Features into an Android Application

Sandeep Ganapa BITS, Pilani Dubai f2008182@bits-dubai.ac.ae Dubai,UAE Dr.S.Vadivel Department Of Computer Science and Engg BITS, Pilani - Dubai Dubai,UAE

AbstractComputing continues to become more and more personalized and accessible. Handheld devices have largely transformed into computing platforms. Mobile phones are no longer just for talkingthey have been capable of carrying data and video for some time. Be it a phone or a tablet, the mobile device is now so capable of general-purpose computing that its becoming more like a PC. Android is one Operating system for mobiles that made this possible. Users would always like to be connected to friends and family and one social networking website that made this possible is Facebook. In this project we will demonstrate how to integrate Facebook Platform features into an Android Application. Specifically, create an android application that accesses Facebook friends of a user. Keywords: Mobile application, Android, Facebook

Components are of the following types: Activity components form the basis of the user interface; usually, each window of the application is controlled by some activity. Service components run in the background, and remain active even if windows are switched. Services can expose interfaces for communication with other applications. Receiver components react asynchronously to messages from other applications. Provider components store data relevant to the application, usually in a database. Such data can be shared across applications. Consider, e.g., a Contacts application for an Android based phone. This application may include several components. There may be activities for viewing the contacts on the phone, and for editing the details of a particular contact. There may be a provider for sharing the Contacts on the phone. Finally there may be service component like syncing contacts to cloud that might run in the background. Component classes and methods The Android SDK provides a base class for each type of component (Activity, Service, Receiver, and Provider), with methods (callbacks) that are run at various points in the life cycle of the associated component. Each component of an application is defined by extending one of the base classes, and overriding the methods in that class. In particular: 1. The Activity class has methods that are run when some activity calls this activity, or returns to this activity.

1. Introduction
Android [1] is Googles new open-source platform for mobile devices. Designed to be a complete software stack, it includes an operating system, middleware, and core applications. Furthermore, it comes with an SDK that provides the tools and APIs necessary to develop new applications for the platform in Java. The SDK can be downloaded from Android Developer website. Eclipse[2] IDE indigo has been used to create the application. This application also uses open source Java library Android Facebook SDK [4] available for download under the Apache License, Version 2.0[3].

2. Overview of Android
In Androids application model, an application is a package of components, each of which can be instantiated and run as necessary (possibly even by other applications).

2. The Service class has a method that is run when some component binds to this service. 3. The Receiver class has a method that is run when a message is sent to this receiver. 4. The Provider class has methods to query and update the data stored by this provider. Android application contains one or more than one Activity, the coding for these activities are done in. Java files while the UI coding for these activities are done in .xml files. To create an activity, we must create a subclass of Activity (or an existing subclass of it). In our subclass, we need to implement callback methods that the system calls when the activity transitions between various states of its lifecycle, such as when the activity is being created, stopped, resumed, or destroyed. The two most important callback methods are: 1. OnCreate (): This method must be implemented. This method is called when the activity is first created. Within this implementation, the essential components of an activity are initialized. Most importantly, setContentView () to define the layout for the activity's user interface. onPause() : The system calls this method as the first indication that the user is leaving an activity This is usually where any changes that should be persisted beyond the current user session are committed.

2. Facebook Graph API and FQL

2.

The user interface for an activity is provided by a hierarchy of viewsobjects derived from the View class. Each view controls a particular rectangular space within the activity's window and can respond to user interaction. For example, a view might be a button that initiates an action when the user touches it. Android provides a number of ready-made views that you can use to design and organize your layout. "Widgets" are views that provide a visual (and interactive) element for the screen, such as a button, text field, checkbox, or just an image. The most common way to define a layout using views is with an XML layout file saved in the application resources. For each XML created resource id is generated. The layout can be set as the UI for an activity with setContentView (), passing the resource ID for the layout. The AndroidManifest.xml File Every application has an AndroidManifest.xml file in its root directory. The manifest presents essential information about the application to the Android system, information that the system must have before it can run any of the application's code. It also describes the components of the application the activities, services, broadcast receivers, and content providers that the application is composed of. It names the classes that implement each of the components and publishes their capabilities. These declarations let the Android system know what the components are and under what conditions they can be launched.

Facebook implements the concept of Social graph. Social Graph is the network of connections that exist through which people communicate and share information. The figure above depicts a typical social graph where each user is represented by a node and relationships among them are represented by edges. In 2010, Facebook introduced Graph API [5] which allows developers access to every object in Facebooks database: users, photos, videos, statuses, conversations, places, and their relations with each other. Every object in the social graph has a unique ID and properties of these objects can be accessed by requesting https://graph.facebook.com/ID. Alternatively, people and pages with usernames can be accessed using their username as an ID. For example the queries https://graph.facebook.com/cocacola and https://graph.facebook.com/40796308305 both return same response as shown below: { "id": "40796308305", "name": "Coca-Cola", "picture": "http://profile.ak.fbcdn.net/hprofile-aksnc4/276879_40796308305_1578420141_s.jpg" , "link": "http://www.facebook.com/cocacola", "likes": 36387860, "category": "Food/beverages", "website": "http://www.coca-cola.com", "username": "coca-cola", "founded": "1886" } All responses are JSON objects. FQL (Facebook Query Language) is Facebooks SQL alternative to access data from the Graph API. It provides for some advanced features not available in the Graph API,

including batching multiple queries into a single call. FQL queries can be run against huge number of tables [4] ex: user, photo, place etc. Queries are of the form SELECT [fields] FROM [table] WHERE [conditions]. Example: SELECT uid, name, pic_square FROM user WHERE uid = me() OR uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) . This query fetches uid, name and profile pic of the active user and friends.

3.Facebook SDK- Methods and Interfaces


As mentioned above Facebook SDK is an open source java library that is available for download at GIT HUB. Facebook SDK consists of the following methods and interfaces[6]: Methods : API Requests: These methods can be implemented to make requests to server using GRAPH API or FQL. Some of the override methods are: a) String request(String graphPath) MalformedURL Exception,IOException. throws

Helpers: These methods help with the Facebook integrations. Some of the override methods are : a) long getAccessExpires() b) String getAccessToken() c) String getAppId() d) boolean isSessionValid() e) void setAccessExpires(long time) f) void setAccessExpiresIn(String expiresIn) g) void setAccessToken(String token) h) void setAppId(String appId) Interfaces: Facebook SDK provides two interfaces namely DialogListener interface and RequestListener interface. DialogListener: The DialogListener Interface provides the callback methods for the Dialog methods. Some of the callback methods are : a) b) c) d) void onCancel() void onComplete(Bundle values) void onError(DialogError de) void onFacebookError(FacebookError fbe)

b) String request(String graphPath, Bundle parameters) throws MalformedURLException, IOException c) String request(String graphPath, Bundle parameters, String httpMethod) throws MalformedURL Exception, IOException

RequestListener: The RequestListener Interface provides the callback methods for asynchronous request methods: a) void onComplete(String response, Object state) b) void onFacebookError(FacebookError fbe, Object state) c) void onFileNotFoundException(FileNotFoundException ex, Object state) d) void onIOException(IOException ex, Object state) e) void onMalformedURLException(MalformedURL Exception ex, Object state)

Async API Requests: These methods are asynchronous i.e. they run on a background thread and publish result on the UI thread and are typically used to implement long tasks such as accessing Facebook profile pictures, accessing friend list etc. Authentication: These methods can be implemented to initiate the user authentication and app authorization flow, Log out the user from Facebook, Check if the user session is valid. Override methods are : a) void request(String graphPath, RequestListener listener) b) void request(String graphPath, RequestListener listener, final Object state) c) void request(String graphPath, Bundle parameters, Request Listener listener) d) void logout(final Context context, final RequestListener listener) Dialogs: These methods can be used to provide a simple, consistent interface to display dialogs to users. Override methods: a) void dialog(Context context, String action, DialogListener listener). b) void dialog(Context context, String action, Bundle parameters, DialogListener listener)

4. Single Sign ON (SSO) And Access Token:


The Facebook SDK for Android takes a mobile web approach to authentication rather than a native one. For this approach, the SDK uses the Facebook web-based authentication dialog inside a WebView. This is an interesting approach for a couple of reasons: It reduces the complexity of implementing OAuth native to the application. Probably as important, it wins the user's trust by displaying the same standard and familiar login and permission dialogs as seen when using Facebook on regular browsers. Facebook SDK provides an access control feature entitled SSO, which if implemented allows user to authorize our app without typing their Facebook username and password. This is accomplished by sharing intent with the official, native Facebook Android application. The following scenarios arise while logging in:

1.

Official Native Facebook Application installed and logged in: In this case our application leverages Facebook app authentication via Single Sign On. Official Native Facebook Application installed and not logged in: User is presented with the login Dialog screen of that of the official native Facebook which on completion logs the user in both the applications. Official Native Facebook Application not installed: If the single sign-on method is not defined or the native Facebook application is not present, the SDK will default to the WebView approach for authentication/login.

2.

d) Enter a Min SDK Version. This is an integer that indicates the minimum API Level required to properly run the application. Entering this here automatically sets the minSdkVersion attribute in the <uses-sdk> of the Android Manifest file. Click Finish.

3.

Once Finish is clicked, the following files and directories will be created for the project automatically: Component Src/ Description Includes the stub Activity Java file. All other Java files for the application go in the directory. (e.g., Android 2.3) Includes the android.jar file that the application will build against. This is determined by the build target that we have chosen in the New Project Wizard. Contains the Java files generated by ADT, such as the R.java file and interfaces created from AIDL files. Initially empty. Used for storing raw asset files A folder for application resources, such as drawable files, layout files, string values, etc. The Android Manifest for the project This file contains project settings, such as the build target. This files is integral to the project, as such, it should be maintained in a Source Revision Control system. It should never be edited manually to edit project properties, right-click the project folder and select "Properties"

After the user logs in-or if the user is already logged into his Facebook app-the OAuth authorization process will prompt user to accept/decline our apps attempt to access resources from his account and show all the resources that will accessed by our app. Once the user accepts, the Official Facebook is closed and the user is redirected to our app, passing the access token, expiration and other parameters from the Facebooks OAuth server. Using the passed access token future requests to the Facebook server is made.

<Android Version>/

5. Creating an Android Project in Eclipse with ADT:


The New Project Wizard dramatically simplifies project setup. To create a new project, simply do the following: Select File > New > Project Select Android > Android Project, and click Next Select the contents for the project: Enter a Project Name. This will be the name of the folder where the project is created. Under Contents, select Create new project in workspace. Select the project workspace location. Under Target, select an Android target to be used as the project's Build Target. The Build Target specifies which Android platform the application will be built against. Under Properties, fill in all necessary fields. a) Enter an Application name. This is the humanreadable title for the application the name that will appear on the Android device. b) Enter a Package name. This is the package namespace (following the same rules as for packages in the Java programming language) where all the source code will reside.(I have named it Fbook and I will be referencing to this project as Fbook through this paper). c) Select Create Activity and enter a name for the main Activity class. gen/

assets/

res/ AndroidManifiest.xml

default.properties

Now that the android project is created it is time to integrate Facebook SDK. Firstly, Facebook SDK needs to be imported in to the eclipse IDE environment. To do this from the top menu select new android project > create from existing project; provide the location of Facebook SDK that was downloaded from github.

Facebook SDK is now available as a separate library project. To integrate it with the Fbook project, Add Facebook sdk as library from the android pane of the properties window. Facebook SDK is now fully integrated and all the methods, interfaces available in the SDK are now available to us from our project.

keytool -exportcert -alias androiddebugkey keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64 where ~ corresponds to the location of the android SDK folder, generally located at C:\Users\<user>\.android\ .

The snap shot above shows the Facebook sdk package under the library section of the formerly created project (Fbook).

6.REGISTERING THE ANDROID APPLICATION


WITH FACEBOOK Integration with Facebook is based on OAuth 2.0 and requires registering a Facebook application at android apps section of developers.facebook.com/apps as shown in the snap shot below. On successful registration Facebook provides an APP ID that we will be using in our android application. The Facebook SDK project revolves around a central com.facebook.android.Facebook.Facebook class, which allows us to perform various calls to Facebook. It provides us with the functionality of login/logoff, Oauth integration and provides us with generic API to perform various calls to the graph API. We will write an application to access Facebook friends of currently authorized user. Creating Facebook Instance:

private Facebook mFacebook; private AsyncFacebookRunner mAsyncRunner; Facebook kfacebook = new Facebook ("APP_ID); mAsyncRunner = new AsyncFacebookRunner (kfacebook);
/*Using this masyncrunner further requests to the Graph API can be made*/ Getting the access token if any: Registering our application requires an android hash key, which can be generating by running the following query at the command prompt of windows.

private SharedPreferences kPrefs; kPrefs = getPreferences(MODE_PRIVATE); String access_token = kPrefs.getString("access_token", null); long expires =

kPrefs.getLong("access_expires", 0); if(access_token != null) { kfacebook.setAccessToken(access_token); } if(expires != 0) { kfacebook.setAccessExpires(expires);


} Logging In: //Call authorize only if session is not valid i.e.. if access token=null or access token expired.//

// Login/logout toggle case R.id.login: // Toggle the button state. // If coming from login transition to logout. if (mFacebook.isSessionValid()) { AsyncFacebookRunner masyncRunner = new AsyncFacebookRunner(kfacebook); masyncRunner.logout(this.getBaseContext(), new LogoutRequestListener()); } else { Code for logging in as shown in the left . } break; //Exists the application// case R.id..exit: this.finish(); case R.id.getfriends: mSpinner.show(); // Shows status i.e. loading.// // Get the authenticated user's friends// mAsyncRunner.request("me?fields=id,name,picture ", new FriendsRequestListener()); break; default: return false; } return true; }
Handling the response of Get Friends: The get friends request to the graph API returns a json array of friends name, id and profile picture. We need to create a List view to display the list of friends names and pictures. Listview requires us to pass an array list of friend objects with the field id, name and picture. Friend Object: public class Friend { public String id; public String name; public Drawable pic; } Parsing JSON Response: final JSONObject json = new JSONObject(response); d = json.getJSONArray("data"); int l = (d != null ? d.length() : 0); JSONObject o = d.getJSONObject(i); String n = o.getString("name"); String id = o.getString("id"); String picture = o.getString("picture"); Friend f = new Friend(); f.id = id;

if(!kfacebook.isSessionValid()) { kfacebook.authorize(this, new String[] {}, new DialogListener() { @Override public void onComplete(Bundle values) { SharedPreferences.Editor editor = kPrefs.edit(); editor.putString("access_token", kfacebook.getAccessToken()); editor.putLong("access_expires", kfacebook.getAccessExpires()); editor.commit(); } @Override public void onFacebookError(FacebookError error) {} @Override public void onError(DialogError e) {} @Override public void onCancel() {} }); } }
Creating a Menu:

@Override public boolean onPrepareOptionsMenu(Menu menu) { MenuItem loginItem = menu.findItem(R.id.login); MenuItem exit = menu.findItem(R.id.exit); MenuItem getfriendsItem = menu.findItem(R.id.getfriends); if (kfacebook.isSessionValid()) { loginItem.setTitle("Logout"); getfriendsItem.setEnabled(true); } else { loginItem.setTitle("Login"); getfriendsItem.setEnabled(false); // Makes the getfriend menu item unavailable if session not valid i.e. if the user is not logged in // } loginItem.setEnabled(true); return super.onPrepareOptionsMenu(menu); }

Handling the menu selection Items:

@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) {

f.name = n; //Graph API returns a link for profile picture,in order to download the actual bitmap the following is to be done// url = new URL(o.getString("picture")); InputStream is = url.openStream(); drawable = Drawable.createFromStream(is, "tr"); f.pic = drawable; friends.add(f); Handling clicks on the listview : After the retrieval of the friends list from graph api, when the user clicks on a specific friend a dialog will appear from where the user can post on the wall of selected friend. The code for doing so is shown below: String name = d.getJSONObject(position).getString("name"); friendId = d.getJSONObject(position).getLong("uid"); new AlertDialog.Builder(FriendsList.this) .setTitle("Post On Wall") .setMessage("You Are About To Post On " + name+ "'s Wall").setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick( DialogInterface dialog, int which) { Bundle params = new Bundle(); params.putString("to",String.valueOf(friendId)); params.putString("caption", "Fbook"); params.putString("description","My Project"); params.putString("picture","http://i41.tinypic.com/11b7xvc.pn g");params.putString("name","Testing My APP"); facebook.dialog(FriendsList.this,"feed", params, new PostDialogListener()); The entire code for the respective java and xml files is shown below: FBActivity.java: package com.sandeep.fbook; public class FBActivity extends Activity { public static final String APP_ID = "1007049666593__"; private static final String[] PERMISSIONS = new String[] { "publish_stream", }; public static Drawable drawable; private TextView mText; private final ArrayList<Friend> friends = new ArrayList<Friend>(); private FriendsArrayAdapter friendsArrayAdapter; private ListView listView; private Facebook mFacebook; private AsyncFacebookRunner mAsyncRunner; private JSONArray d; String k; Long L;

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); this.getWindow().setFlags(WindowManager.LayoutParams.F LAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_ FULLSCREEN); if (APP_ID == null) { Util.showAlert(this, "Warning","Facebook Applicaton ID must be set"); } setContentView(R.layout.main); listView = (ListView) findViewById(R.id.friendsview); listView.setTextFilterEnabled(true); listView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { try { String name = d.getJSONObject(position).getString("name"); friendId = d.getJSONObject(position).getLong("uid"); new AlertDialog.Builder(FriendsList.this) .setTitle("Post On Wall") .setMessage("You Are About To Post On " + name+ "'s Wall") .setPositiveButton("OK",new DialogInterface.OnClickListener() { @Override public void onClick( DialogInterface dialog,int which) { Bundle params = new Bundle(); params.putString("to",String.valueOf(friendId)); params.putString("caption", "Fbook"); params.putString("description","My Project"); params.putString("picture", "http://i41.tinypic.com/11b7xvc.png"); params.putString("name","Testing My APP"); facebook.dialog(FriendsList.this,"feed", params, new PostDialogListener()); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); friendsArrayAdapter = new FriendsArrayAdapter(this, R.layout.rowlayout,friends); listView.setAdapter(friendsArrayAdapter); mSpinner = new ProgressDialog(listView.getContext()); mSpinner.requestWindowFeature(Window.FEATURE_NO_TI TLE); mSpinner.setMessage("Please Wait :) "); mFacebook = new Facebook(APP_ID); mAsyncRunner = new AsyncFacebookRunner(mFacebook); } public void onActivityResult(int requestCode, int resultCode, Intent data) {

super.onActivityResult(requestCode, resultCode, data); Log.d("FB Sample App", "onActivityResult(): " + requestCode); mFacebook.authorizeCallback(requestCode, resultCode, data); } public class FriendsRequestListener implements com.facebook.android.AsyncFacebookRunner.RequestListene r{ public void onComplete(String response, Object state) { listView.setTextFilterEnabled(true); try { // process the response here: executed in background thread Log.d("Facebook-Example-FriendsRequest", "response.length(): "+ response.length()); Log.d("Facebook-Example-Friends Request", "Response: " + response); int k = 0; final JSONObject json = new JSONObject(response); d = json.getJSONArray("data"); int z = d.length(); int l = (d != null ? d.length() : 0); Log.d("Facebook-Example-Friends Request", "resp " + z); for (int i = 0; i < l; i++) { URL url; k++; Log.d("Facebook-Example-Friends Request", "resp " + k); try { JSONObject o = d.getJSONObject(i); String n = o.getString("name"); String id = o.getString("id"); String picture = o.getString("picture"); Friend f = new Friend(); f.id = id; f.name = n; url = new URL(o.getString("picture")); InputStream is = url.openStream(); drawable = Drawable.createFromStream(is, "tr"); Log.d("fb", "+1"); f.pic = drawable; friends.add(f); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (z == k) { mSpinner.dismiss(); } } // Only the original owner thread can touch its views FBActivity.this.runOnUiThread(new Runnable() { public void run() { friendsArrayAdapter = new FriendsArrayAdapter( FBActivity.this, R.layout.rowlayout, friends); listView.setAdapter(friendsArrayAdapter); friendsArrayAdapter.notifyDataSetChanged(); }});} catch (JSONException e) {

Log.w("Facebook-Example", "JSON Error in response"); } } public void onIOException(IOException e, Object state) { // TODO Auto-generated method stub } publicvoid onFileNotFoundException(FileNotFoundException e, Object state) { // TODO Auto-generated method stub } publicvoid onMalformedURLException(MalformedURLException e, Object state) { // TODO Auto-generated method stub } public void onFacebookError(FacebookError e, Object state) {// TODO Auto-generated method stub } } public final class LoginDialogListener implements com.facebook.android.Facebook.DialogListener { public void onComplete(Bundle values) { // Process onComplete Log.d("FB Sample App", "LoginDialogListener.onComplete()"); // Dispatch on its own thread mHandler.post(new Runnable() { public void run() { mText.setText("Facebook login successful Press Menu"); } }); } public void onFacebookError(FacebookError error) { // Process error Log.d("FB Sample App", "LoginDialogListener.onFacebookError()"); } public void onError(DialogError error) { // Process error message Log.d("FB Sample App", "LoginDialogListener.onError()"); } public void onCancel() { // Process cancel message Log.d("FB Sample App", "LoginDialogListener.onCancel()"); } } listView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String name = d.getJSONObject(position).getString("name"); friendId = d.getJSONObject(position).getLong("uid"); new AlertDialog.Builder(FriendsList.this) .setTitle("Post On Wall") .setMessage("You Are About To Post On " + name+ "'s Wall")

.setPositiveButton("OK",new DialogInterface.OnClickListener() { @Override public void onClick( DialogInterface dialog,int which) { Bundle params = new Bundle(); params.putString("to",String.valueOf(friendId)); params.putString("caption", "Fbook"); params.putString("description","My Project"); params.putString("picture", "http://i41.tinypic.com/11b7xvc.png"); params.putString("name","Testing My APP"); facebook.dialog(FriendsList.this,"feed", params, new PostDialogListener()); } } public class LogoutRequestListener implements RequestListener { public void onComplete(String response) { // Only the original owner thread can touch its views } public void onComplete(String response, Object state) { // TODO Auto-generated method stub } public void onIOException(IOException e, Object state) { // TODO Auto-generated method stub } public void onFileNotFoundException(FileNotFoundException e, Object state) { // TODO Auto-generated method stub } public void onMalformedURLException(MalformedURLException e, Object state) { // TODO Auto-generated method stub } public void onFacebookError(FacebookError e, Object state) {// TODO Auto-generated method stub } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { MenuItem loginItem = menu.findItem(R.id.login); MenuItem exit = menu.findItem(R.id.exit); MenuItem getfriendsItem = menu.findItem(R.id.getfriends); if (kfacebook.isSessionValid()) { loginItem.setTitle("Logout"); getfriendsItem.setEnabled(true);

} else { loginItem.setTitle("Login"); getfriendsItem.setEnabled(false); // Makes the getfriend menu item unavailable if session not valid i.e. if the user is not logged in // } loginItem.setEnabled(true); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Login/logout toggle case R.id.login: // Toggle the button state. // If coming from login transition to logout. if (mFacebook.isSessionValid()) { AsyncFacebookRunner masyncRunner = new AsyncFacebookRunner(kfacebook); masyncRunner.logout(this.getBaseContext(), new LogoutRequestListener()); } else { Code for logging in as shown in the left . } break; //Exists the application// case R.id..exit: this.finish(); case R.id.getfriends: mSpinner.show(); // Shows status i.e. loading.// // Get the authenticated user's friends// mAsyncRunner.request("me?fields=id,name,picture", new FriendsRequestListener()); break; default: return false; } return true; } } Friend.java : package com.sandeep.fbook; import android.graphics.Bitmap; import android.graphics.drawable.*; public class Friend { public String id; public String name; public Drawable pic; } FriendsArrayAdapter : package com.sandeep.fbook; import java.util.ArrayList; import android.app.Activity; import android.content.Context;

import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Filterable; import android.widget.ImageView; import android.widget.TextView; public class FriendsArrayAdapter extends ArrayAdapter<Friend> implements Filterable { private final Activity context; private final ArrayList<Friend> friends; private int resourceId; public ImageView iv; public FriendsArrayAdapter(Activity context, int resourceId, ArrayList<Friend> friends) { super(context, resourceId, friends); this.context = context; this.friends = friends; this.resourceId = resourceId; } @Override public View getView(int position, View convertView, ViewGroup parent) { View rowView = convertView; if (rowView == null) { LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_ INFLATER_SERVICE); rowView = vi.inflate(resourceId, null); } Friend f = friends.get(position); TextView rowTxt = (TextView) rowView.findViewById(R.id.rowtext_top); iv = (ImageView)rowView.findViewById(R.id.imageView1); iv.setImageDrawable(f.pic); rowTxt.setText(f.name); return rowView; } } main.xml : <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/facebookwallpaper" > <TextView android:id="@+id/txt" android:text="@string/hello" android:textColor="@drawable/white" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingRight="10dp" android:paddingLeft="10dp" android:layout_margin="10dp" android:textSize="10sp" android:layout_marginTop="5px"

android:layout_marginBottom="5px" android:layout_marginRight="0px" android:layout_marginLeft="0px" android:gravity="left"/> <ListView android:id="@+id/friendsview" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textFilterEnabled="true" android:background="#005599" android:cacheColorHint="#00000000"/> <TextView android:id="@id/android:empty" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> rowlayout.xml : <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="?android:attr/listPreferredItemHeight" android:padding="10dip" android:cacheColorHint="#00000000" > <ImageView android:id="@+id/imageView1" android:src="@drawable/icon" android:layout_height="50dp" android:layout_width="50dp"></ImageView> <TextView android:id="@+id/rowtext_top" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_vertical" android:text="sample" android:textSize="25sp" android:layout_marginLeft="5dp" android:layout_marginTop="10dp"/> </LinearLayout>

Login Screen Wallpost 7.CONCLUSION In summary, with all upcoming applications and mobile services Google Android is stepping into the next level of Mobile Internet. It is a robust platform; giving developers the tools they need to write powerful, compelling and useful applications consumers will love. In this paper we have demonstrated how easily an android application can be created and how to integrate some of the features of the Facebook platform in to this application. REFERENCES 1.What is Android www.developer.android.com/guide/basics/what-isandroid.html 2.eclipse indigo http://www.eclipse.org/downloads/packages/release/indigo/r 3.Apache License http://www.apache.org/licenses/LICENSE-2.0.html 4.Android Facebook SDK https://github.com/facebook/facebook-android-sdk FriendsList 5. Graph API http://developers.facebook.com/docs/reference/api/ 6.Methods and Interfaces http://developers.facebook.com/docs/reference/androidsdk/

7.Mark.L.Murphy, Busy Coders Guide to Android Development(2011) 8.Mark.L.Murphy,CommonsWare,Android.Programming.Tut orials.Mar.2011

You might also like