WARNING AND NOTICE

All tricks in this blog are only for educational purpose. Learn these tricks only for your knowledge. Please donot try these to harm any one. We will not take any responsibility in any case. All softwares and tools on this site are here for private purposes only and If you want to use a software for business purpose, please purchase it. I do not host many of these tools. I Post links that I have found from numerous Search engines. I will not be responsible for any of harm you will do by using these tools.

Readmore

Friday, June 24, 2011

Using Facebook SDK in Android development, Part 2

In this part, I show you an android application, which logging in to Facebook, then get the Facebook ID.
Please go through the first part of the tutorial, before reading this post.

1. Step
Create a new Android project in Eclipse, choose "create project from existing source", and set the location to: "Your Facebook SDK"\facebook. In my case it's D:\facebook android sdk\facebook.
sdk
2. Step
Create a new empty Android project, and open project properties/android. Hit Add in the Library section, add the facebook project.
sdk
3. Step
Change the main.xml like this:

  1. xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.         android:orientation="vertical" android:layout_width="fill_parent"
  4.         android:layout_height="fill_parent">
  5.         <TextView android:layout_width="fill_parent" android:id="@+id/textFacebook"
  6.                 android:gravity="center_horizontal" android:layout_height="wrap_content"
  7.                 android:text="@string/welcome" android:layout_alignParentTop="true" />
  8.         <Button android:text="@string/enter" android:id="@+id/buttonLogin"
  9.                 android:layout_below="@+id/textFacebook"
  10.                 android:layout_centerHorizontal="true" android:layout_width="wrap_content"
  11.                 android:layout_height="wrap_content" android:layout_marginTop="30dip">Button>
  12.         <ProgressBar android:id="@+id/progressLogin"
  13.                 android:layout_centerInParent="true" android:layout_width="wrap_content"
  14.                 android:visibility="gone" android:layout_height="wrap_content">ProgressBar>
  15. RelativeLayout>
And add Internet Permission to the AndroidManifest.xml:

  1.         <uses-permission android:name="android.permission.INTERNET">
  2.         uses-permission>
My strings.xml looks like this:

  1. xml version="1.0" encoding="utf-8"?>
  2. <resources>
  3.     <string name="welcome">Welcome string>
  4.     <string name="app_name">FacebookTeststring>
  5.     <string name="enter">Log in to Facebookstring>
  6. resources>
3. Step
Create an abstract class, for the Facebook connection. Don't forget to insert your app id!

  1. public abstract class FBConnectionActivity extends Activity {
  2.         public static final String TAG = "FACEBOOK";
  3.         private Facebook mFacebook;
  4.         public static final String APP_ID = "INSERT YOUR APP ID";
  5.         private AsyncFacebookRunner mAsyncRunner;
  6.         private static final String[] PERMS = new String[] { "read_stream" };
  7.         private SharedPreferences sharedPrefs;
  8.         private Context mContext;
  9.         private TextView username;
  10.         private ProgressBar pb;
  11.         public void setConnection() {
  12.                 mContext = this;
  13.                 mFacebook = new Facebook(APP_ID);
  14.                 mAsyncRunner = new AsyncFacebookRunner(mFacebook);
  15.         }
  16.         public void getID(TextView txtUserName, ProgressBar progbar) {
  17.                 username = txtUserName;
  18.                 pb = progbar;
  19.                 if (isSession()) {
  20.                         Log.d(TAG, "sessionValid");
  21.                         mAsyncRunner.request("me", new IDRequestListener());
  22.                 } else {
  23.                         // no logged in, so relogin
  24.                         Log.d(TAG, "sessionNOTValid, relogin");
  25.                         mFacebook.authorize(this, PERMS, new LoginDialogListener());
  26.                 }
  27.         }
  28.         public boolean isSession() {
  29.                 sharedPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
  30.                 String access_token = sharedPrefs.getString("access_token", "x");
  31.                 Long expires = sharedPrefs.getLong("access_expires", -1);
  32.                 Log.d(TAG, access_token);
  33.                 if (access_token != null && expires != -1) {
  34.                         mFacebook.setAccessToken(access_token);
  35.                         mFacebook.setAccessExpires(expires);
  36.                 }
  37.                 return mFacebook.isSessionValid();
  38.         }
  39.         private class LoginDialogListener implements DialogListener {
  40.                 @Override
  41.                 public void onComplete(Bundle values) {
  42.                         Log.d(TAG, "LoginONComplete");
  43.                         String token = mFacebook.getAccessToken();
  44.                         long token_expires = mFacebook.getAccessExpires();
  45.                         Log.d(TAG, "AccessToken: " + token);
  46.                         Log.d(TAG, "AccessExpires: " + token_expires);
  47.                         sharedPrefs = PreferenceManager
  48.                                         .getDefaultSharedPreferences(mContext);
  49.                         sharedPrefs.edit().putLong("access_expires", token_expires)
  50.                                         .commit();
  51.                         sharedPrefs.edit().putString("access_token", token).commit();
  52.                         mAsyncRunner.request("me", new IDRequestListener());
  53.                 }
  54.                 @Override
  55.                 public void onFacebookError(FacebookError e) {
  56.                         Log.d(TAG, "FacebookError: " + e.getMessage());
  57.                 }
  58.                 @Override
  59.                 public void onError(DialogError e) {
  60.                         Log.d(TAG, "Error: " + e.getMessage());
  61.                 }
  62.                 @Override
  63.                 public void onCancel() {
  64.                         Log.d(TAG, "OnCancel");
  65.                 }
  66.         }
  67.         private class IDRequestListener implements RequestListener {
  68.                 @Override
  69.                 public void onComplete(String response, Object state) {
  70.                         try {
  71.                                 Log.d(TAG, "IDRequestONComplete";);
  72.                                 Log.d(TAG, "Response: " + response.toString());
  73.                                 JSONObject json = Util.parseJson(response);
  74.                                 final String id = json.getString("id");
  75.                                 final String name = json.getString("name");
  76.                                 FBConnectionActivity.this.runOnUiThread(new Runnable() {
  77.                                         public void run() {
  78.                                                 username.setText("Welcome: " + name+"\n ID: "+id);
  79.                                                 pb.setVisibility(ProgressBar.GONE);
  80.                                         }
  81.                                 });
  82.                         } catch (JSONException e) {
  83.                                 Log.d(TAG, "JSONException: " + e.getMessage());
  84.                         } catch (FacebookError e) {
  85.                                 Log.d(TAG, "FacebookError: " + e.getMessage());
  86.                         }
  87.                 }
  88.                 @Override
  89.                 public void onIOException(IOException e, Object state) {
  90.                         Log.d(TAG, "IOException: " + e.getMessage());
  91.                 }
  92.                 @Override
  93.                 public void onFileNotFoundException(FileNotFoundException e,
  94.                                 Object state) {
  95.                         Log.d(TAG, "FileNotFoundException: " + e.getMessage());
  96.                 }
  97.                 @Override
  98.                 public void onMalformedURLException(MalformedURLException e,
  99.                                 Object state) {
  100.                         Log.d(TAG, "MalformedURLException: " + e.getMessage());
  101.                 }
  102.                 @Override
  103.                 public void onFacebookError(FacebookError e, Object state) {
  104.                         Log.d(TAG, "FacebookError: " + e.getMessage());
  105.                 }
  106.         }
  107.         @Override
  108.         protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  109.                 mFacebook.authorizeCallback(requestCode, resultCode, data);
  110.         }
  111. }
4. Step
Add the connection activity to the manifest:

  1. <activity android:name=".FBConnectionActivity&quot; android:label="@string/app_name">activity>
5. Step
Change the Main activity like that:

  1. public class Main extends FBConnectionActivity {
  2.         private TextView txtUserName;
  3.         private ProgressBar pbLogin;
  4.         private Button btnLogin;
  5.        
  6.     @Override
  7.     public void onCreate(Bundle savedInstanceState) {
  8.         super.onCreate(savedInstanceState);
  9.         setContentView(R.layout.main);
  10.        
  11.         txtUserName = (TextView) findViewById(R.id.textFacebook);
  12.         pbLogin = (ProgressBar) findViewById(R.id.progressLogin);
  13.         btnLogin = (Button) findViewById(R.id.buttonLogin);
  14.                 btnLogin.setOnClickListener(new OnClickListener() {
  15.                         @Override
  16.                         public void onClick(View arg0) {
  17.                                 pbLogin.setVisibility(ProgressBar.VISIBLE);
  18.                                 setConnection();
  19.                                 getID(txtUserName, pbLogin);
  20.                         }
  21.                 });
  22.     }
  23. }
And see the result:
sdk
In the next part, I'll show you, how to get additional Facebook datas!

VIA : helloandroid.com