Tutorials Android Using Facebook SDK in Android Example

Using Facebook SDK in Android Example

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

  1. Login to Facebook
  2. Share status message to Facebook wall
  3. 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

  1. 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.
  2. 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.
  3. 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);
	}

}

Output

Facebook Android Example

Total
0
Shares
guest
50 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Macy Chan
Macy Chan
8 years ago

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?

Deveti Putnik
Deveti Putnik
8 years ago
Reply to  Macy Chan

Same here…

harsha
harsha
8 years ago

but where the user login details taken for new user

Swaminathan
Swaminathan
8 years ago

code works finely…i wanna share url with image on facebook wall.. can you post me the code to do it

Mike Howard
Mike Howard
8 years ago

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.

Sami
Sami
8 years ago

Life Saver !

Risk Rømer
Risk Rømer
8 years ago

can this be achieved without fragments? Would like to reach earlier devices to Level 11. Thanks!

javatechig
javatechig
8 years ago
Reply to  Risk Rømer

@Risk, very much doable with simple activity.

Uzair Majid
Uzair Majid
8 years ago

can someone please explain the working of this code?
some methods are pretty confusing ?

javatechig
javatechig
8 years ago
Reply to  Uzair Majid

Please do refer to official facebook developer portal for complete documentation

https://developers.facebook.com/docs/android

amr khamis
amr khamis
8 years ago

worked like charm 😀 thank you 😉
where can i get the token so that i post photos in other activities ??!!

javatechig
javatechig
8 years ago
Reply to  amr khamis

you may store the token.

javatechig
javatechig
8 years ago

Download the sdk. It comes with sample that fetching profile pic from fb.

https://developers.facebook.com/docs/android

bidhu
bidhu
8 years ago

Hi it allowed me to login only once and that to i couldn’t post any status update or upload any image.

Aakash Gupta
Aakash Gupta
8 years ago

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?

Bincy
Bincy
8 years ago

Thanks…….i want to share url on facebook wall.. can you post me the code to do it

abhai
abhai
8 years ago

the username is not getting displayed in my case. i checked everything.

James Cosgrave
James Cosgrave
7 years ago

Is this discussion still active ?

Thirumalai
Thirumalai
7 years ago

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.

André Luiz Teste
André Luiz Teste
7 years ago

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.

Vikram Arora
Vikram Arora
7 years ago

thanks a lot

libin
libin
7 years ago

unfortunately stopped in my device

JavaTechig
JavaTechig
7 years ago
Reply to  libin

Please do paste the error log. Difficult to trace without it.

JavaTechig
JavaTechig
7 years ago

Don’t have the example but you can refer the api document here

https://developers.facebook.com/docs/reference/android/current

Randy Rowell
Randy Rowell
7 years ago

Thank you. This is 10 times better than the official facebook documentation.

Nilanchala Panigrahy
Nilanchala Panigrahy
7 years ago

Looks like some issue with the Facebook sdks. At runtime the sdks is not found. Rebuild or restart eclipse.

Nitesh Kumar
Nitesh Kumar
7 years ago

Nice one. Thanks.

Priya
Priya
7 years ago

I am getting the error NullPointerException: Argument ‘applicationId’ cannot be null

Nilanchala Panigrahy
Nilanchala Panigrahy
7 years ago
Reply to  Priya

Did you create a app in Facebook developer console?

Nilanchala Panigrahy
Nilanchala Panigrahy
7 years ago

Facebook SDK 2.9

JavaTechig
JavaTechig
7 years ago

what is the error ?

devendra
devendra
7 years ago

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.

Devendra Sharma
Devendra Sharma
7 years ago

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……

Krishna Pillai
Krishna Pillai
7 years ago

Hi Can you please explain the role of UILifeCycleHelper in this code ? Why is it used ?

Manish Raaz
Manish Raaz
7 years ago

com.facebook.widget.loginbutton error in xml showing n also r cannot be resolved to a variable android

Sudan Tuladhar
Sudan Tuladhar
7 years ago
Reply to  Manish Raaz

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.

Nilanchala Panigrahy
Nilanchala Panigrahy
7 years ago
Reply to  Sudan Tuladhar

Thanks @Sudan Tuladhar

Sam
Sam
7 years ago

perfect tutorial friend, thanks

Manikandan Kuppusamy
Manikandan Kuppusamy
7 years ago

thanks for posting but i am not able to get any data from user.. user returns null value how to fix this ???

Nilanchala Panigrahy
Nilanchala Panigrahy
7 years ago

Did you request for appropriate permissions?

Pratik Gondil
Pratik Gondil
6 years ago

I have an error “no library found for com.facebook.Request”

saurabh kalani
saurabh kalani
6 years ago

how to integrate facebook page with first i want to display my facebook page

Androd Mangalore
Androd Mangalore
6 years ago

how to download shource code

Androd Mangalore
Androd Mangalore
6 years ago

where is source code

Tech Morphosis
Tech Morphosis
6 years ago

Superb dude .. I used ur Twitter and facebook code , everything works great 🙂
How do I get email ID from facebook API ?

HiMangi PatEl
HiMangi PatEl
6 years ago

plss share source code for this demo

Vaghela Divyrajsinh
Vaghela Divyrajsinh
6 years ago
Reply to  HiMangi PatEl

BUs Copy Copy Or Kuch Nahi……………………….This Example Is Done, So u Try Completly Work

Ashutosh
Ashutosh
6 years ago

THIS IS A VERY USEFUL BUT I NEED FULL SOURCE CODE

Vinoth Vino
Vinoth Vino
6 years ago

Facebook SDK version?

StackTips
StackTips
6 years ago

Older version of Facebook v 3.2

Previous Post
Android Tutorials

Android Popup Menu Example

Next Post
Java Tutorials

CountDownLatch and Java Concurrency Example

Related Posts
By clicking “Allow All”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. Cookie Notice
Allow All
50
0
Would love your thoughts, please comment.x
()
x