Monday, February 18, 2013

Sign up with Facebook in Android | Getting Facebook user detail in Android | Facebook Integration In Android

Hello friends,
        Today I am going to share very important code for Signup/Login with facebook in our application(Getting Facebook access token, user-id, user-name, email-id, gender, birthday etc). For that I am using Facebook graph API. Step by step process is given below hope it will help some one-

1)Print Screen:
a)Main page:

b)After Facebook button clicked:


2)Second step go to Facebook developer web-sight and create an app from below url-
http://developers.facebook.com/

a)For new application click on Apps button first-

b)After that click on "+Create New App"-

c)Then fill App Name: button below and press continue button-

d)Finally copy App ID/API Key


3)Create a new android application
4)Create a new Activity class "MainActivity.java"and copy below code-

package com.example.signupwithfacebook;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Facebook.DialogListener;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class MainActivity extends Activity {
Button btnFacebook;
Context context = MainActivity.this;
// please put your APP-ID below
String Facebook_APP_ID = "YOUR-APP-KEY";// don't forget most important
Facebook facebook = new Facebook(Facebook_APP_ID);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
private SharedPreferences mPrefs;
String access_token;
Boolean Connectiontimeout = false;
String imageURL = "";
Bitmap profilePic;
ImageView userImage;
TextView textName;
TextView textUserName;
TextView textGender;
String name = "";
String userName = "";
String gender = "";

@Override
/**
* @author manish
*/
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnFacebook = (Button) findViewById(R.id.btn_facebook);
userImage = (ImageView) findViewById(R.id.imageView1);
textName = (TextView) findViewById(R.id.textView2);
textUserName = (TextView) findViewById(R.id.textView4);
textGender = (TextView) findViewById(R.id.textView6);
/**
* on click facebook button
*/
btnFacebook.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
/**
* check for network connectivity
*/
if (isNetworkAvailable(context) == true) {
accessTokenFacebook();

} else {
Toast.makeText(MainActivity.this, "No Network Connection",
Toast.LENGTH_SHORT).show();
}

}
});
}

/**
* Network testing method you can put it into Helper/Utility class also
*/
public static boolean isNetworkAvailable(Context mContext) {

ConnectivityManager cm = (ConnectivityManager) mContext
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
Log.e("Network Testing", "***Available***");
return true;
}
Log.e("Network Testing", "***Not Available***");
return false;
}

/**
* Function to get facebook Access token
* */

public void accessTokenFacebook() {

mPrefs = getPreferences(MODE_PRIVATE);
access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
// Log.e("Facebook token", access_token);

if (access_token != null) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}

/**
* Only call authorize if the access_token has expired.
*/
if (!facebook.isSessionValid()) {

facebook.authorize(this, new String[] {}, new DialogListener() {
public void onComplete(Bundle values) {
try {
JSONObject me = new JSONObject(facebook.request("me"));
SharedPreferences.Editor editor = mPrefs.edit();
String id = me.getString("id");
System.out
.println("******facebook.getAccessToken()****"
+ facebook.getAccessToken());
editor.putString("userid", id);
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
new getFacebookData().execute();
} catch (Exception e) {
// TODO: handle exception
}
}

public void onFacebookError(FacebookError error) {
}

public void onError(DialogError e) {
}

public void onCancel() {
}
});
} else {
new getFacebookData().execute();
}

}

/**
* Async class for getting facebook data in background thread
*
* @author manish
*
*/

public class getFacebookData extends AsyncTask<String, Void, String> {

ProgressDialog pd = null;

@Override
protected void onPreExecute() {
pd = ProgressDialog.show(MainActivity.this, "Please wait",
"Loading please wait..", true);
pd.setCancelable(true);

}

@Override
protected String doInBackground(String... params) {
fbUserProfile();
return null;
}

@Override
protected void onPostExecute(String result) {
pd.dismiss();
if (Connectiontimeout != true) {
textName.setText(name);
textUserName.setText(userName);
textGender.setText(gender);
userImage.setImageBitmap(profilePic);
} else {
Toast.makeText(MainActivity.this, "Connection Time out",
Toast.LENGTH_SHORT).show();
}
}

}

/**
* getting user facebook data from facebook server
*/
public void fbUserProfile() {

try {
access_token = mPrefs.getString("access_token", null);
JSONObject jsonObj = null;
JSONObject jsonObjData = null;
JSONObject jsonObjUrl = null;
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 50000);
HttpConnectionParams.setSoTimeout(httpParameters, 50000);

HttpClient client = new DefaultHttpClient(httpParameters);

String requestURL = "https://graph.facebook.com/me?fields=picture,id,name,gender,username&access_token="
+ access_token;
Log.i("Request URL:", "---" + requestURL);
HttpGet request = new HttpGet(requestURL);

HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String webServiceInfo = "";

while ((webServiceInfo = rd.readLine()) != null) {
Log.i("Service Response:", "---" + webServiceInfo);
jsonObj = new JSONObject(webServiceInfo);
jsonObjData = jsonObj.getJSONObject("picture");
jsonObjUrl = jsonObjData.getJSONObject("data");
name = jsonObj.getString("name");
userName = jsonObj.getString("username");
gender = jsonObj.getString("gender");
imageURL = jsonObjUrl.getString("url");
profilePic = BitmapFactory.decodeStream((InputStream) new URL(
imageURL).getContent());
}

} catch (Exception e) {
Connectiontimeout = true;
}
}

}


5)Create a layout "activity_main.xml" and copy below code-

<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"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/btn_facebook"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:background="@drawable/ic_launcher" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/textView"
        android:layout_marginTop="20dp"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/textView1"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="20dp"
            android:text="user name:" />

        <TextView
            android:id="@+id/textView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/textView3"
            android:layout_alignLeft="@+id/textView2" />

        <TextView
            android:id="@+id/textView5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/textView3"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="20dp"
            android:text="your gender:" />

        <TextView
            android:id="@+id/textView6"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/textView5"
            android:layout_alignLeft="@+id/textView4" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_alignRight="@+id/textView3"
            android:layout_marginTop="5dp"
            android:text="your name:" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/textView1"
            android:layout_alignBottom="@+id/textView1"
            android:layout_centerHorizontal="true" />

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_alignLeft="@+id/textView6"
            android:layout_below="@+id/textView6"
            android:layout_marginTop="17dp"
            android:scaleType="fitXY"
            android:src="@drawable/camera_image" />
    </RelativeLayout>

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/btn_facebook"
        android:layout_alignBottom="@+id/btn_facebook"
        android:layout_centerHorizontal="true"
        android:text="Click facebok button"
        android:textSize="20sp" />

</RelativeLayout>

6)And now open your manifest.xml file and give below two permission-

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

7)Last and Important step run your application and enjoy :)

Thanks,

             


18 comments:

  1. Hi manish,

    You have any sample code for posting msg on facebook wall, please let me know..

    ReplyDelete
  2. Hi Manish here login is working but user profile data is not displayed could you please look on it.

    ReplyDelete
    Replies
    1. It should work dear, Please try with other user-id may be this one private.
      And if you did not got any thing please check Facebook graph api may be there is any change. I did not check earlier.

      Delete
  3. Hi Manish ,Good Tutorial but how can i get key hash ??

    ReplyDelete
    Replies
    1. Firstly, to generate your key hash on your local computer, run Java's keytool utility (which should be on your console's path) against the Android debug keystore. This is, by default, in your home .android directory).
      On Linux-
      keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64

      On Windows-
      keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | openssl sha1 -binary | openssl base64

      For more help read facebook help page-
      https://developers.facebook.com/docs/android/getting-started/facebook-sdk-for-android/

      Delete
  4. Hi Manish Login is Working But User Profile are Not Showing ..Please Check

    ReplyDelete
    Replies
    1. Hi Ashok, Actually Facebook change their API now. So please check new Facebook Developer APIs.

      Delete
  5. HI Manish How to get the list of all friends ? Plz tell me....

    ReplyDelete
  6. @Manish Sir,
    How cn we access offical facebook fans page data using GRAPH API..?
    And when i run this code connection tiome-out toast show?

    ReplyDelete
  7. your code is not workink.. please suggest another way to fetch data.....it is very urgent....

    ReplyDelete
  8. There is no crash issue , but did not receive any data.

    ReplyDelete
  9. Can u plz share me the source code...

    ReplyDelete
    Replies
    1. Actually facebook updated their library and way to do things so kindly follow the facebook developers website.

      Delete
  10. provied the new json link .. by the help of json we get user information

    ReplyDelete
  11. Hi,
    the onComplete() is not working for me, can u help in this ???

    ReplyDelete
    Replies
    1. It is old Facebook SDK, please follow Facebook developer for latest update.

      And there is no direct Native SDK for debit/credit card implementation. You need any third party library to implement.

      Delete
  12. Hello Manish,
    Have you demo for sign Up in Facebook and back to our app with registered data. Because I have to use that data and go forword.

    ReplyDelete
    Replies
    1. Try Facebook developer blog for signup, it will return you public profile data.

      Delete