This tutorial explains how to how to use Facebook SDK APIs in Android. This tutorial allows user to login to Facebook first and then allows to do following things
- Login to Facebook
- Share status message to Facebook wall
- Share Image to Facebook wall
This example using Facebook SDK 3.0 for Android which is available for free download from the Facebook’s developer console. This Facebook SDK comes with almost all the functionality of the native Facebook app to your own Android app. Follow the below steps
Creating an App on Facebook
Before integrating Facebook SDK to your android app you have to create a Facebook app on your Facebook developer console. Visit Facebook developer console and create a new Facebook application. Once you create the application you will get an app id, which is used to uniquely distinguish your application from others. This AppID will be used along with each of the request we make to Facebook server. Don’t get panic, sometime it takes some time to make your application go live.
Using Facebook SDK in Android
- Now you have created an Facebook app in developer console and you are ready to start with our Android app. You may create a new project or import an existing one.
- Import Facebook SDK to your eclipse workspace and make sure it builds successfully. Once it builds we have to attach the Facebook library project to your Android project. The easiest way to attach the SDK is to add it as an Android library by going to the project’s properties.
- Now do the following changes to your application manifest file. Put the following code before </application> tag. Make sure you are using your own AppID obtained from Facebook developer console.
<activity android:name="com.facebook.LoginActivity" android:theme="@android:style/Theme.Translucent.NoTitleBar" /> <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/app_id" />
Note: Make sure that you have give android.permission.INTERNET permission in your application manifest file.
Activity Layout
Now define layout for your activity class. In this example, We have three sample buttons.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:facebook="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal" android:orientation="vertical" android:padding="20dp" > <com.facebook.widget.LoginButton android:id="@+id/fb_login_button" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" facebook:confirm_logout="false" facebook:fetch_user_info="true" /> <TextView android:id="@+id/user_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_margin="10dp" android:textSize="18sp" /> <Button android:id="@+id/update_status" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/update_status" /> <Button android:id="@+id/post_image" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/post_image" /> </LinearLayout>
Activity Java Class
public class FBActivity extends FragmentActivity { private LoginButton loginBtn; private Button postImageBtn; private Button updateStatusBtn; private TextView userName; private UiLifecycleHelper uiHelper; private static final List<String> PERMISSIONS = Arrays.asList("publish_actions"); private static String message = "Sample status posted from android app"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); uiHelper = new UiLifecycleHelper(this, statusCallback); uiHelper.onCreate(savedInstanceState); setContentView(R.layout.activity_facebook); userName = (TextView) findViewById(R.id.user_name); loginBtn = (LoginButton) findViewById(R.id.fb_login_button); loginBtn.setUserInfoChangedCallback(new UserInfoChangedCallback() { @Override public void onUserInfoFetched(GraphUser user) { if (user != null) { userName.setText("Hello, " + user.getName()); } else { userName.setText("You are not logged"); } } }); postImageBtn = (Button) findViewById(R.id.post_image); postImageBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { postImage(); } }); updateStatusBtn = (Button) findViewById(R.id.update_status); updateStatusBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { } }); buttonsEnabled(false); } private Session.StatusCallback statusCallback = new Session.StatusCallback() { @Override public void call(Session session, SessionState state, Exception exception) { if (state.isOpened()) { buttonsEnabled(true); Log.d("FacebookSampleActivity", "Facebook session opened"); } else if (state.isClosed()) { buttonsEnabled(false); Log.d("FacebookSampleActivity", "Facebook session closed"); } } }; public void buttonsEnabled(boolean isEnabled) { postImageBtn.setEnabled(isEnabled); updateStatusBtn.setEnabled(isEnabled); } public void postImage() { if (checkPermissions()) { Bitmap img = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher); Request uploadRequest = Request.newUploadPhotoRequest( Session.getActiveSession(), img, new Request.Callback() { @Override public void onCompleted(Response response) { Toast.makeText(FBActivity.this, "Photo uploaded successfully", Toast.LENGTH_LONG).show(); } }); uploadRequest.executeAsync(); } else { requestPermissions(); } } public void postStatusMessage() { if (checkPermissions()) { Request request = Request.newStatusUpdateRequest( Session.getActiveSession(), message, new Request.Callback() { @Override public void onCompleted(Response response) { if (response.getError() == null) Toast.makeText(FBActivity.this, "Status updated successfully", Toast.LENGTH_LONG).show(); } }); request.executeAsync(); } else { requestPermissions(); } } public boolean checkPermissions() { Session s = Session.getActiveSession(); if (s != null) { return s.getPermissions().contains("publish_actions"); } else return false; } public void requestPermissions() { Session s = Session.getActiveSession(); if (s != null) s.requestNewPublishPermissions(new Session.NewPermissionsRequest( this, PERMISSIONS)); } @Override public void onResume() { super.onResume(); uiHelper.onResume(); buttonsEnabled(Session.getActiveSession().isOpened()); } @Override public void onPause() { super.onPause(); uiHelper.onPause(); } @Override public void onDestroy() { super.onDestroy(); uiHelper.onDestroy(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); uiHelper.onActivityResult(requestCode, resultCode, data); } @Override public void onSaveInstanceState(Bundle savedState) { super.onSaveInstanceState(savedState); uiHelper.onSaveInstanceState(savedState); } }
i can only run the App successfully once even I commented the sentence “buttonsEnabled(false); “. how can i do if i want to send several status by clicking the button for several times?
Same here…
but where the user login details taken for new user
code works finely…i wanna share url with image on facebook wall.. can you post me the code to do it
Perfect example… I was messing around on the Facebook dev pages for a few hours and didn’t get very far. This sample exactly what I was looking for.
Life Saver !
can this be achieved without fragments? Would like to reach earlier devices to Level 11. Thanks!
@Risk, very much doable with simple activity.
can someone please explain the working of this code?
some methods are pretty confusing ?
Please do refer to official facebook developer portal for complete documentation
https://developers.facebook.com/docs/android
worked like charm 😀 thank you 😉
where can i get the token so that i post photos in other activities ??!!
you may store the token.
Download the sdk. It comes with sample that fetching profile pic from fb.
https://developers.facebook.com/docs/android
Hi it allowed me to login only once and that to i couldn’t post any status update or upload any image.
Thanks for the code. I want to access email ID too..
Whenever i try user.getProperty(“email”); my application crashes. I add email permission in List PERMISSIONS = Arrays.asList(“publish_actions”,”email”);
Can you tell what i m doing wrong?
Thanks…….i want to share url on facebook wall.. can you post me the code to do it
the username is not getting displayed in my case. i checked everything.
Is this discussion still active ?
Hi very nice tutorial.But update status and post image function is not working.It ask me again to login.When Im done it does nothing.Kindly help me.Thanks in Advance.
your application worked on my phone but did not work on the phone from my brother, when I click the login button and does not open the facebook page which asks permission to access and post.
thanks a lot
unfortunately stopped in my device
Please do paste the error log. Difficult to trace without it.
Don’t have the example but you can refer the api document here
https://developers.facebook.com/docs/reference/android/current
Thank you. This is 10 times better than the official facebook documentation.
Looks like some issue with the Facebook sdks. At runtime the sdks is not found. Rebuild or restart eclipse.
Nice one. Thanks.
I am getting the error NullPointerException: Argument ‘applicationId’ cannot be null
Did you create a app in Facebook developer console?
Facebook SDK 2.9
what is the error ?
hi m devendra sharma android developer.
i have one problem get use in this code.
only one fb id ragister and another id login in this code than they are login but share an image. so plz help me.
hi i have one problem get.
only one user first login than image share.
but second user login and than image are not post.
plz help me……
Hi Can you please explain the role of UILifeCycleHelper in this code ? Why is it used ?
com.facebook.widget.loginbutton error in xml showing n also r cannot be resolved to a variable android
com.facebook.widget.LoginButton has been changed to com.facebook.login.widget.LoginButton in version 4 of Facebook SDK. Using that should fix the error with both xml and R.
Thanks @Sudan Tuladhar
perfect tutorial friend, thanks
thanks for posting but i am not able to get any data from user.. user returns null value how to fix this ???
Did you request for appropriate permissions?
I have an error “no library found for com.facebook.Request”
how to integrate facebook page with first i want to display my facebook page
how to download shource code
where is source code
Superb dude .. I used ur Twitter and facebook code , everything works great 🙂
How do I get email ID from facebook API ?
plss share source code for this demo
BUs Copy Copy Or Kuch Nahi……………………….This Example Is Done, So u Try Completly Work
THIS IS A VERY USEFUL BUT I NEED FULL SOURCE CODE
Facebook SDK version?
Older version of Facebook v 3.2