Started integrating Facebook SDK 3.0

pull/14/head
Sam Bosley 13 years ago
parent 28e0c93ecb
commit cd4d90715c

@ -1,17 +0,0 @@
/**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.facebook.android;
public interface AuthListener {
public void onFBAuthSucceed();
public void onFBAuthFail(String error);
public void onFBAuthCancel();
}

@ -1,89 +0,0 @@
/*
* Copyright 2010 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.android;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import com.facebook.android.Facebook.DialogListener;
public class LoginButton extends Button {
public static final int REQUEST_CODE_FACEBOOK = 21421;
private Facebook mFb;
private AuthListener mListener;
private String[] mPermissions;
private Activity mActivity;
public LoginButton(Context context) {
super(context);
}
public LoginButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public LoginButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void init(final Activity activity, final Facebook fb, AuthListener listener) {
init(activity, fb, listener, new String[] {});
}
public void init(final Activity activity, final Facebook fb, AuthListener listener,
final String[] permissions) {
mActivity = activity;
mFb = fb;
mPermissions = permissions;
mListener = listener;
setOnClickListener(new ButtonOnClickListener());
}
private final class ButtonOnClickListener implements OnClickListener {
public void onClick(View arg0) {
mFb.authorize(mActivity, mPermissions, REQUEST_CODE_FACEBOOK,
new LoginDialogListener());
}
}
private final class LoginDialogListener implements DialogListener {
public void onComplete(Bundle values) {
mListener.onFBAuthSucceed();
}
public void onFacebookError(FacebookError error) {
mListener.onFBAuthFail(error.getMessage());
}
public void onError(DialogError error) {
mListener.onFBAuthFail(error.getMessage());
}
public void onCancel() {
mListener.onFBAuthCancel();
}
}
}

@ -5,12 +5,10 @@
*/ */
package com.todoroo.astrid.actfm; package com.todoroo.astrid.actfm;
import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.net.MalformedURLException; import java.util.Arrays;
import java.util.Random; import java.util.Random;
import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import android.app.AlertDialog; import android.app.AlertDialog;
@ -31,6 +29,7 @@ import android.text.method.PasswordTransformationMethod;
import android.text.style.ClickableSpan; import android.text.style.ClickableSpan;
import android.text.style.UnderlineSpan; import android.text.style.UnderlineSpan;
import android.util.DisplayMetrics; import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View; import android.view.View;
import android.view.View.OnClickListener; import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams; import android.view.ViewGroup.LayoutParams;
@ -41,13 +40,10 @@ import android.widget.ScrollView;
import android.widget.TextView; import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.facebook.android.AsyncFacebookRunner; import com.facebook.Session;
import com.facebook.android.AsyncFacebookRunner.RequestListener; import com.facebook.SessionState;
import com.facebook.android.AuthListener; import com.facebook.UiLifecycleHelper;
import com.facebook.android.Facebook; import com.facebook.widget.LoginButton;
import com.facebook.android.FacebookError;
import com.facebook.android.LoginButton;
import com.facebook.android.Util;
import com.google.android.googlelogin.GoogleLoginServiceConstants; import com.google.android.googlelogin.GoogleLoginServiceConstants;
import com.google.android.googlelogin.GoogleLoginServiceHelper; import com.google.android.googlelogin.GoogleLoginServiceHelper;
import com.timsu.astrid.GCMIntentService; import com.timsu.astrid.GCMIntentService;
@ -97,7 +93,7 @@ import com.todoroo.astrid.service.TaskService;
* @author Tim Su <tim@astrid.com> * @author Tim Su <tim@astrid.com>
* *
*/ */
public class ActFmLoginActivity extends SherlockFragmentActivity implements AuthListener { public class ActFmLoginActivity extends SherlockFragmentActivity {
public static final String APP_ID = "183862944961271"; //$NON-NLS-1$ public static final String APP_ID = "183862944961271"; //$NON-NLS-1$
@ -131,8 +127,8 @@ public class ActFmLoginActivity extends SherlockFragmentActivity implements Auth
private final ActFmInvoker actFmInvoker = new ActFmInvoker(); private final ActFmInvoker actFmInvoker = new ActFmInvoker();
private Random rand; private Random rand;
private Facebook facebook; // private Facebook facebook;
private AsyncFacebookRunner facebookRunner; // private AsyncFacebookRunner facebookRunner;
protected TextView errors; protected TextView errors;
public static final String SHOW_TOAST = "show_toast"; //$NON-NLS-1$ public static final String SHOW_TOAST = "show_toast"; //$NON-NLS-1$
@ -173,6 +169,8 @@ public class ActFmLoginActivity extends SherlockFragmentActivity implements Auth
rand = new Random(DateUtilities.now()); rand = new Random(DateUtilities.now());
uiHelper = new UiLifecycleHelper(this, callback);
uiHelper.onCreate(savedInstanceState);
initializeUI(); initializeUI();
getWindow().setFormat(PixelFormat.RGBA_8888); getWindow().setFormat(PixelFormat.RGBA_8888);
@ -196,15 +194,23 @@ public class ActFmLoginActivity extends SherlockFragmentActivity implements Auth
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
uiHelper.onResume();
StatisticsService.sessionStart(this); StatisticsService.sessionStart(this);
} }
@Override @Override
protected void onPause() { protected void onPause() {
super.onPause(); super.onPause();
uiHelper.onPause();
StatisticsService.sessionPause(); StatisticsService.sessionPause();
} }
@Override
protected void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
@Override @Override
protected void onStop() { protected void onStop() {
StatisticsService.sessionStop(this); StatisticsService.sessionStop(this);
@ -254,16 +260,15 @@ public class ActFmLoginActivity extends SherlockFragmentActivity implements Auth
@SuppressWarnings("nls") @SuppressWarnings("nls")
protected void initializeUI() { protected void initializeUI() {
facebook = new Facebook(APP_ID); // facebook = new Facebook(APP_ID);
facebookRunner = new AsyncFacebookRunner(facebook); // facebookRunner = new AsyncFacebookRunner(facebook);
errors = (TextView) findViewById(R.id.error); errors = (TextView) findViewById(R.id.error);
LoginButton loginButton = (LoginButton) findViewById(R.id.fb_login); LoginButton loginButton = (LoginButton) findViewById(R.id.fb_login);
if(loginButton == null) if(loginButton == null)
return; return;
loginButton.init(this, facebook, this, new String[] { "email", loginButton.setReadPermissions(Arrays.asList("email", "offline_access", "publish_stream"));
"offline_access", "publish_stream" });
View googleLogin = findViewById(R.id.gg_login); View googleLogin = findViewById(R.id.gg_login);
if(AmazonMarketStrategy.isKindleFire()) if(AmazonMarketStrategy.isKindleFire())
@ -474,75 +479,92 @@ public class ActFmLoginActivity extends SherlockFragmentActivity implements Auth
// --- facebook handler // --- facebook handler
public void onFBAuthSucceed() { private void onSessionStateChange(Session session, SessionState state, Exception exception) {
createUserAccountFB(); if (state.isOpened()) {
Log.e("fb-login", "State opened");
} else if (state.isClosed()) {
Log.e("fb-login", "State closed");
} }
public void onFBAuthFail(String error) {
DialogUtilities.okDialog(this, getString(R.string.actfm_ALA_title),
android.R.drawable.ic_dialog_alert, error, null);
}
@Override
public void onFBAuthCancel() {
// do nothing
}
private ProgressDialog progressDialog;
/**
* Create user account via FB
*/
public void createUserAccountFB() {
progressDialog = DialogUtilities.progressDialog(this,
getString(R.string.DLG_please_wait));
facebookRunner.request("me", new SLARequestListener()); //$NON-NLS-1$
} }
private class SLARequestListener implements RequestListener { private UiLifecycleHelper uiHelper;
private final Session.StatusCallback callback = new Session.StatusCallback() {
@Override @Override
public void onComplete(String response, Object state) { public void call(Session session, SessionState state, Exception exception) {
JSONObject json; onSessionStateChange(session, state, exception);
try {
json = Util.parseJson(response);
String firstName = json.getString("first_name"); //$NON-NLS-1$
String lastName = json.getString("last_name"); //$NON-NLS-1$
String email = json.getString("email"); //$NON-NLS-1$
authenticate(email, firstName, lastName, ActFmInvoker.PROVIDER_FACEBOOK,
facebook.getAccessToken());
StatisticsService.reportEvent(StatisticsConstants.ACTFM_LOGIN_FB);
} catch (FacebookError e) {
handleError(e);
} catch (JSONException e) {
handleError(e);
}
}
@Override
public void onFacebookError(FacebookError e, Object state) {
handleError(e);
}
@Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
handleError(e);
}
@Override
public void onIOException(IOException e, Object state) {
handleError(e);
}
@Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
handleError(e);
} }
};
} // public void onFBAuthSucceed() {
// createUserAccountFB();
// }
//
// public void onFBAuthFail(String error) {
// DialogUtilities.okDialog(this, getString(R.string.actfm_ALA_title),
// android.R.drawable.ic_dialog_alert, error, null);
// }
//
// @Override
// public void onFBAuthCancel() {
// // do nothing
// }
//
private ProgressDialog progressDialog;
//
// /**
// * Create user account via FB
// */
// public void createUserAccountFB() {
// progressDialog = DialogUtilities.progressDialog(this,
// getString(R.string.DLG_please_wait));
// facebookRunner.request("me", new SLARequestListener()); //$NON-NLS-1$
// }
//
// private class SLARequestListener implements RequestListener {
//
// @Override
// public void onComplete(String response, Object state) {
// JSONObject json;
// try {
// json = Util.parseJson(response);
// String firstName = json.getString("first_name"); //$NON-NLS-1$
// String lastName = json.getString("last_name"); //$NON-NLS-1$
// String email = json.getString("email"); //$NON-NLS-1$
//
// authenticate(email, firstName, lastName, ActFmInvoker.PROVIDER_FACEBOOK,
// facebook.getAccessToken());
// StatisticsService.reportEvent(StatisticsConstants.ACTFM_LOGIN_FB);
// } catch (FacebookError e) {
// handleError(e);
// } catch (JSONException e) {
// handleError(e);
// }
// }
//
// @Override
// public void onFacebookError(FacebookError e, Object state) {
// handleError(e);
// }
//
// @Override
// public void onFileNotFoundException(FileNotFoundException e,
// Object state) {
// handleError(e);
// }
//
// @Override
// public void onIOException(IOException e, Object state) {
// handleError(e);
// }
//
// @Override
// public void onMalformedURLException(MalformedURLException e,
// Object state) {
// handleError(e);
// }
//
// }
// --- utilities // --- utilities
@ -658,6 +680,8 @@ public class ActFmLoginActivity extends SherlockFragmentActivity implements Auth
@SuppressWarnings("nls") @SuppressWarnings("nls")
@Override @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) { protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CANCELED) if (resultCode == RESULT_CANCELED)
return; return;
@ -666,25 +690,27 @@ public class ActFmLoginActivity extends SherlockFragmentActivity implements Auth
String accounts[] = data.getStringArrayExtra( String accounts[] = data.getStringArrayExtra(
GoogleLoginServiceConstants.ACCOUNTS_KEY); GoogleLoginServiceConstants.ACCOUNTS_KEY);
credentialsListener.getCredentials(accounts); credentialsListener.getCredentials(accounts);
} else if (requestCode == LoginButton.REQUEST_CODE_FACEBOOK) {
if (data == null)
return;
String error = data.getStringExtra("error");
if (error == null) {
error = data.getStringExtra("error_type");
}
String token = data.getStringExtra("access_token");
if (error != null) {
onFBAuthFail(error);
} else if (token == null) {
onFBAuthFail("Something went wrong! Please try again.");
} else {
facebook.setAccessToken(token);
onFBAuthSucceed();
} }
errors.setVisibility(View.GONE); // else if (requestCode == LoginButton.REQUEST_CODE_FACEBOOK) {
} else if (requestCode == REQUEST_CODE_GOOGLE) { // if (data == null)
// return;
//
// String error = data.getStringExtra("error");
// if (error == null) {
// error = data.getStringExtra("error_type");
// }
// String token = data.getStringExtra("access_token");
// if (error != null) {
// onFBAuthFail(error);
// } else if (token == null) {
// onFBAuthFail("Something went wrong! Please try again.");
// } else {
// facebook.setAccessToken(token);
// onFBAuthSucceed();
// }
// errors.setVisibility(View.GONE);
// }
else if (requestCode == REQUEST_CODE_GOOGLE) {
if (data == null) if (data == null)
return; return;
String email = data.getStringExtra(ActFmGoogleAuthActivity.RESULT_EMAIL); String email = data.getStringExtra(ActFmGoogleAuthActivity.RESULT_EMAIL);

@ -0,0 +1,15 @@
Facebook welcomes contributions to our SDKs.
All contributors must sign a CLA (contributor license agreement) here:
https://developers.facebook.com/opensource/cla
To contribute on behalf of your employer, sign the company CLA
To contribute on behalf of yourself, sign the individual CLA
All contributions:
1/ MUST be be licensed using the Apache License, Version 2.0
2/ authors MAY retain copyright by adding their copyright notice to the appropriate flies
More information on the Apache License can be found here: http://www.apache.org/foundation/license-faq.html

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

@ -0,0 +1,61 @@
THE FOLLOWING SETS FORTH ATTRIBUTION NOTICES FOR THIRD PARTY SOFTWARE THAT MAY BE CONTAINED IN PORTIONS OF THE FACEBOOK PRODUCT.
-----
The following software may be included in this product: Android. This software contains the following license and notice below:
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

@ -1,24 +0,0 @@
This open source Java library allows you to integrate Facebook into your Android application. Except as otherwise noted, the Facebook Android SDK is licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html)
Getting Started
===============
See our [Android SDK Getting Started Guide](https://developers.facebook.com/docs/mobile/android/build/)
Sample Applications
===============
This library includes three sample applications to guide you in development.
* __simple__: A bare-bones app that demonstrates authorization, making API calls, and invoking a dialog.
* __stream__: This slightly beefier application lets you view your news feed.
* __Hackbook__: This includes Single Sign On implementation (SSO), sample API calls, and advanced features like Get new Permissions, Run sample FQL Query and Graph API Explorer. Check out [Hackbook for Android](https://developers.facebook.com/docs/mobile/android/hackbook/)
Report Issues/Bugs
===============
[Bugs](https://developers.facebook.com/bugs)
[Questions](http://facebook.stackoverflow.com/questions/tagged/android)

@ -0,0 +1,32 @@
Facebook SDK for Android
========================
This open-source library allows you to integrate Facebook into your Android app.
Learn more about about the provided samples, documentation, integrating the SDK into your app, accessing source code, and more at https://developers.facebook.com/android-beta
TRY IT OUT
1. Test your install; build and run the project at facebook-android-sdk-3.0.b/samples/HelloFacebookSample (To avoid test signing issues, run this on a device that does not have Facebook for Android installed, or debug the signed sample binaries provided in facebook-android-sdk-3.0.b/bin)
2. Check-out the tutorials available online at https://developers.facebook.com/docs/getting-started/facebook-sdk-for-android/3.0/
3. Start coding! Visit https://developers.facebook.com/android-beta for tutorials and reference documentation.
LICENSE
Except as otherwise noted, the Facebook SDK for Android is licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html).
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
DEVELOPER TERMS
- By enabling Facebook integrations, including through this SDK, you can share information with Facebook, including information about peoples use of your app. Facebook will use information received in accordance with our Data Use Policy (https://www.facebook.com/about/privacy/), including to provide you with insights about the effectiveness of your ads and the use of your app. These integrations also enable us and our partners to serve ads on and off Facebook.
- You may limit your sharing of information with us by updating the Insights control in the developer tool (https://developers.facebook.com/apps/<app_id>/advanced).
- If you use a Facebook integration, including to share information with us, you agree and confirm that you have provided appropriate and sufficiently prominent notice to and obtained the appropriate consent from your users regarding such collection, use, and disclosure (including, at a minimum, through your privacy policy). You further agree that you will not share information with us about children under the age of 13.
- You agree to comply with all applicable laws and regulations and also agree to our Terms (https://www.facebook.com/policies/), including our Platform Policies (https://developers.facebook.com/policy/) and Advertising Guidelines, as applicable (https://www.facebook.com/ad_guidelines.php).
By using the Facebook SDK for Android you agree to these terms.

@ -1,14 +0,0 @@
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system use,
# "build.properties", and override values to adapt the script to your
# project structure.
# Indicates whether an apk should be generated for each density.
split.density=false
# Project target.
target=android-8
android.library.reference.1=../../../newdialog/facebook-android-sdk/facebook

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/login_down" />
<item android:drawable="@drawable/login" /> <!-- default -->
</selector>

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/logout_down" />
<item android:drawable="@drawable/logout" /> <!-- default -->
</selector>

@ -1,11 +0,0 @@
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight">
<TextView
android:id="@+id/connection_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="26sp"
android:textColor="@color/lite_blue"
android:paddingLeft="5dp" />
</RelativeLayout>

@ -1,14 +0,0 @@
<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="@color/black">
<CheckBox
android:id="@+id/fields_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/fields_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

@ -1,11 +0,0 @@
<?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="@color/black">
<ListView
android:id="@+id/friends_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>

@ -1,9 +0,0 @@
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_api_item"
android:padding="10dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:gravity="center_vertical"
android:textSize="20sp" />

@ -1,8 +0,0 @@
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight">
<CheckBox
android:id="@+id/permission_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>

@ -1,11 +0,0 @@
<?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="@color/black">
<ListView
android:id="@+id/places_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>

@ -1,5 +0,0 @@
<ImageView android:id="@+id/imageView1" xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/splash"
android:scaleType="fitXY"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />

@ -1,10 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="white">#ffffff</color>
<color name="black">#000000</color>
<color name="green">#23cf34</color>
<color name="orange">#E47833</color>
<color name="lite_blue">#4E78A0</color>
<color name="blue">#0000FF</color>
<color name="grey">#FF909090</color>
</resources>

@ -1,25 +0,0 @@
package com.facebook.android;
import com.facebook.android.Facebook.DialogListener;
/**
* Skeleton base class for RequestListeners, providing default error handling.
* Applications should handle these error conditions.
*/
public abstract class BaseDialogListener implements DialogListener {
@Override
public void onFacebookError(FacebookError e) {
e.printStackTrace();
}
@Override
public void onError(DialogError e) {
e.printStackTrace();
}
@Override
public void onCancel() {
}
}

@ -1,20 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.facebook.android"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon"
android:label="@string/app_name"
android:debuggable="true">
<activity android:name=".Example"
android:label="@string/app_name"
android:configChanges="keyboardHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-sdk android:minSdkVersion="3"/>
</manifest>

@ -1,14 +0,0 @@
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system use,
# "build.properties", and override values to adapt the script to your
# project structure.
# Indicates whether an apk should be generated for each density.
split.density=false
android.library.reference.1=../../facebook/
# Project target.
target=android-3

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/login_down" />
<item android:drawable="@drawable/login" /> <!-- default -->
</selector>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 KiB

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/logout_down" />
<item android:drawable="@drawable/logout" /> <!-- default -->
</selector>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

@ -1,65 +0,0 @@
<?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/white"
android:gravity="center_horizontal">
<com.facebook.android.LoginButton
android:id="@+id/login"
android:src="@drawable/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="30dp"
/>
<TextView android:id="@+id/txt"
android:text="@string/hello"
android:textColor="@drawable/black"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<Button android:id="@+id/uploadButton"
android:text="@string/upload"
android:visibility="invisible"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="20dp"
android:paddingLeft="20dp"
android:layout_margin="20dp"
/>
<Button android:id="@+id/requestButton"
android:text="@string/request"
android:visibility="invisible"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="20dp"
android:paddingLeft="20dp"
android:layout_margin="20dp"
/>
<Button android:id="@+id/postButton"
android:text="@string/post"
android:visibility="invisible"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="20dp"
android:paddingLeft="20dp"
android:layout_margin="20dp"
/>
<Button android:id="@+id/deletePostButton"
android:text="@string/delete"
android:visibility="invisible"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="20dp"
android:paddingLeft="20dp"
android:layout_margin="20dp"
/>
</LinearLayout>

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<drawable name="white">#ffffff</drawable>
<drawable name="black">#000000</drawable>
</resources>

@ -1,10 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Facebook SDK Example</string>
<string name="request">Request!</string>
<string name="hello">Hello World!</string>
<string name="upload">Upload Photo</string><string name="post">Wall Post!</string>
<string name="delete">Delete Post</string>
</resources>

@ -1,23 +0,0 @@
package com.facebook.android;
import com.facebook.android.Facebook.DialogListener;
/**
* Skeleton base class for RequestListeners, providing default error
* handling. Applications should handle these error conditions.
*
*/
public abstract class BaseDialogListener implements DialogListener {
public void onFacebookError(FacebookError e) {
e.printStackTrace();
}
public void onError(DialogError e) {
e.printStackTrace();
}
public void onCancel() {
}
}

@ -1,40 +0,0 @@
package com.facebook.android;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import android.util.Log;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
/**
* Skeleton base class for RequestListeners, providing default error
* handling. Applications should handle these error conditions.
*
*/
public abstract class BaseRequestListener implements RequestListener {
public void onFacebookError(FacebookError e, final Object state) {
Log.e("Facebook", e.getMessage());
e.printStackTrace();
}
public void onFileNotFoundException(FileNotFoundException e,
final Object state) {
Log.e("Facebook", e.getMessage());
e.printStackTrace();
}
public void onIOException(IOException e, final Object state) {
Log.e("Facebook", e.getMessage());
e.printStackTrace();
}
public void onMalformedURLException(MalformedURLException e,
final Object state) {
Log.e("Facebook", e.getMessage());
e.printStackTrace();
}
}

@ -1,281 +0,0 @@
/*
* Copyright 2010 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.android;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import com.facebook.android.SessionEvents.AuthListener;
import com.facebook.android.SessionEvents.LogoutListener;
public class Example extends Activity {
// Your Facebook Application ID must be set before running this example
// See http://www.facebook.com/developers/createapp.php
public static final String APP_ID = "175729095772478";
private LoginButton mLoginButton;
private TextView mText;
private Button mRequestButton;
private Button mPostButton;
private Button mDeleteButton;
private Button mUploadButton;
private Facebook mFacebook;
private AsyncFacebookRunner mAsyncRunner;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (APP_ID == null) {
Util.showAlert(this, "Warning", "Facebook Applicaton ID must be " +
"specified before running this example: see Example.java");
}
setContentView(R.layout.main);
mLoginButton = (LoginButton) findViewById(R.id.login);
mText = (TextView) Example.this.findViewById(R.id.txt);
mRequestButton = (Button) findViewById(R.id.requestButton);
mPostButton = (Button) findViewById(R.id.postButton);
mDeleteButton = (Button) findViewById(R.id.deletePostButton);
mUploadButton = (Button) findViewById(R.id.uploadButton);
mFacebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(mFacebook);
SessionStore.restore(mFacebook, this);
SessionEvents.addAuthListener(new SampleAuthListener());
SessionEvents.addLogoutListener(new SampleLogoutListener());
mLoginButton.init(this, mFacebook);
mRequestButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mAsyncRunner.request("me", new SampleRequestListener());
}
});
mRequestButton.setVisibility(mFacebook.isSessionValid() ?
View.VISIBLE :
View.INVISIBLE);
mUploadButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Bundle params = new Bundle();
params.putString("method", "photos.upload");
URL uploadFileUrl = null;
try {
uploadFileUrl = new URL(
"http://www.facebook.com/images/devsite/iphone_connect_btn.jpg");
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn= (HttpURLConnection)uploadFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
int length = conn.getContentLength();
byte[] imgData =new byte[length];
InputStream is = conn.getInputStream();
is.read(imgData);
params.putByteArray("picture", imgData);
} catch (IOException e) {
e.printStackTrace();
}
mAsyncRunner.request(null, params, "POST",
new SampleUploadListener(), null);
}
});
mUploadButton.setVisibility(mFacebook.isSessionValid() ?
View.VISIBLE :
View.INVISIBLE);
mPostButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mFacebook.dialog(Example.this, "feed",
new SampleDialogListener());
}
});
mPostButton.setVisibility(mFacebook.isSessionValid() ?
View.VISIBLE :
View.INVISIBLE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
mFacebook.authorizeCallback(requestCode, resultCode, data);
}
public class SampleAuthListener implements AuthListener {
public void onAuthSucceed() {
mText.setText("You have logged in! ");
mRequestButton.setVisibility(View.VISIBLE);
mUploadButton.setVisibility(View.VISIBLE);
mPostButton.setVisibility(View.VISIBLE);
}
public void onAuthFail(String error) {
mText.setText("Login Failed: " + error);
}
}
public class SampleLogoutListener implements LogoutListener {
public void onLogoutBegin() {
mText.setText("Logging out...");
}
public void onLogoutFinish() {
mText.setText("You have logged out! ");
mRequestButton.setVisibility(View.INVISIBLE);
mUploadButton.setVisibility(View.INVISIBLE);
mPostButton.setVisibility(View.INVISIBLE);
}
}
public class SampleRequestListener extends BaseRequestListener {
public void onComplete(final String response, final Object state) {
try {
// process the response here: executed in background thread
Log.d("Facebook-Example", "Response: " + response.toString());
JSONObject json = Util.parseJson(response);
final String name = json.getString("name");
// then post the processed result back to the UI thread
// if we do not do this, an runtime exception will be generated
// e.g. "CalledFromWrongThreadException: Only the original
// thread that created a view hierarchy can touch its views."
Example.this.runOnUiThread(new Runnable() {
public void run() {
mText.setText("Hello there, " + name + "!");
}
});
} catch (JSONException e) {
Log.w("Facebook-Example", "JSON Error in response");
} catch (FacebookError e) {
Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
}
}
}
public class SampleUploadListener extends BaseRequestListener {
public void onComplete(final String response, final Object state) {
try {
// process the response here: (executed in background thread)
Log.d("Facebook-Example", "Response: " + response.toString());
JSONObject json = Util.parseJson(response);
final String src = json.getString("src");
// then post the processed result back to the UI thread
// if we do not do this, an runtime exception will be generated
// e.g. "CalledFromWrongThreadException: Only the original
// thread that created a view hierarchy can touch its views."
Example.this.runOnUiThread(new Runnable() {
public void run() {
mText.setText("Hello there, photo has been uploaded at \n" + src);
}
});
} catch (JSONException e) {
Log.w("Facebook-Example", "JSON Error in response");
} catch (FacebookError e) {
Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
}
}
}
public class WallPostRequestListener extends BaseRequestListener {
public void onComplete(final String response, final Object state) {
Log.d("Facebook-Example", "Got response: " + response);
String message = "<empty>";
try {
JSONObject json = Util.parseJson(response);
message = json.getString("message");
} catch (JSONException e) {
Log.w("Facebook-Example", "JSON Error in response");
} catch (FacebookError e) {
Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
}
final String text = "Your Wall Post: " + message;
Example.this.runOnUiThread(new Runnable() {
public void run() {
mText.setText(text);
}
});
}
}
public class WallPostDeleteListener extends BaseRequestListener {
public void onComplete(final String response, final Object state) {
if (response.equals("true")) {
Log.d("Facebook-Example", "Successfully deleted wall post");
Example.this.runOnUiThread(new Runnable() {
public void run() {
mDeleteButton.setVisibility(View.INVISIBLE);
mText.setText("Deleted Wall Post");
}
});
} else {
Log.d("Facebook-Example", "Could not delete wall post");
}
}
}
public class SampleDialogListener extends BaseDialogListener {
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
Log.d("Facebook-Example", "Dialog Success! post_id=" + postId);
mAsyncRunner.request(postId, new WallPostRequestListener());
mDeleteButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mAsyncRunner.request(postId, new Bundle(), "DELETE",
new WallPostDeleteListener(), null);
}
});
mDeleteButton.setVisibility(View.VISIBLE);
} else {
Log.d("Facebook-Example", "No wall post made");
}
}
}
}

@ -1,139 +0,0 @@
/*
* Copyright 2010 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.android;
import com.facebook.android.BaseRequestListener;
import com.facebook.android.SessionEvents.AuthListener;
import com.facebook.android.SessionEvents.LogoutListener;
import com.facebook.android.Facebook.DialogListener;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageButton;
public class LoginButton extends ImageButton {
private Facebook mFb;
private Handler mHandler;
private SessionListener mSessionListener = new SessionListener();
private String[] mPermissions;
private Activity mActivity;
public LoginButton(Context context) {
super(context);
}
public LoginButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public LoginButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void init(final Activity activity, final Facebook fb) {
init(activity, fb, new String[] {});
}
public void init(final Activity activity, final Facebook fb,
final String[] permissions) {
mActivity = activity;
mFb = fb;
mPermissions = permissions;
mHandler = new Handler();
setBackgroundColor(Color.TRANSPARENT);
setAdjustViewBounds(true);
setImageResource(fb.isSessionValid() ?
R.drawable.logout_button :
R.drawable.login_button);
drawableStateChanged();
SessionEvents.addAuthListener(mSessionListener);
SessionEvents.addLogoutListener(mSessionListener);
setOnClickListener(new ButtonOnClickListener());
}
private final class ButtonOnClickListener implements OnClickListener {
public void onClick(View arg0) {
if (mFb.isSessionValid()) {
SessionEvents.onLogoutBegin();
AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(mFb);
asyncRunner.logout(getContext(), new LogoutRequestListener());
} else {
mFb.authorize(mActivity, mPermissions,
new LoginDialogListener());
}
}
}
private final class LoginDialogListener implements DialogListener {
public void onComplete(Bundle values) {
SessionEvents.onLoginSuccess();
}
public void onFacebookError(FacebookError error) {
SessionEvents.onLoginError(error.getMessage());
}
public void onError(DialogError error) {
SessionEvents.onLoginError(error.getMessage());
}
public void onCancel() {
SessionEvents.onLoginError("Action Canceled");
}
}
private class LogoutRequestListener extends BaseRequestListener {
public void onComplete(String response, final Object state) {
// callback should be run in the original thread,
// not the background thread
mHandler.post(new Runnable() {
public void run() {
SessionEvents.onLogoutFinish();
}
});
}
}
private class SessionListener implements AuthListener, LogoutListener {
public void onAuthSucceed() {
setImageResource(R.drawable.logout_button);
SessionStore.save(mFb, getContext());
}
public void onAuthFail(String error) {
}
public void onLogoutBegin() {
}
public void onLogoutFinish() {
SessionStore.clear(getContext());
setImageResource(R.drawable.login_button);
}
}
}

@ -1,146 +0,0 @@
/*
* Copyright 2010 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.android;
import java.util.LinkedList;
public class SessionEvents {
private static LinkedList<AuthListener> mAuthListeners =
new LinkedList<AuthListener>();
private static LinkedList<LogoutListener> mLogoutListeners =
new LinkedList<LogoutListener>();
/**
* Associate the given listener with this Facebook object. The listener's
* callback interface will be invoked when authentication events occur.
*
* @param listener
* The callback object for notifying the application when auth
* events happen.
*/
public static void addAuthListener(AuthListener listener) {
mAuthListeners.add(listener);
}
/**
* Remove the given listener from the list of those that will be notified
* when authentication events occur.
*
* @param listener
* The callback object for notifying the application when auth
* events happen.
*/
public static void removeAuthListener(AuthListener listener) {
mAuthListeners.remove(listener);
}
/**
* Associate the given listener with this Facebook object. The listener's
* callback interface will be invoked when logout occurs.
*
* @param listener
* The callback object for notifying the application when log out
* starts and finishes.
*/
public static void addLogoutListener(LogoutListener listener) {
mLogoutListeners.add(listener);
}
/**
* Remove the given listener from the list of those that will be notified
* when logout occurs.
*
* @param listener
* The callback object for notifying the application when log out
* starts and finishes.
*/
public static void removeLogoutListener(LogoutListener listener) {
mLogoutListeners.remove(listener);
}
public static void onLoginSuccess() {
for (AuthListener listener : mAuthListeners) {
listener.onAuthSucceed();
}
}
public static void onLoginError(String error) {
for (AuthListener listener : mAuthListeners) {
listener.onAuthFail(error);
}
}
public static void onLogoutBegin() {
for (LogoutListener l : mLogoutListeners) {
l.onLogoutBegin();
}
}
public static void onLogoutFinish() {
for (LogoutListener l : mLogoutListeners) {
l.onLogoutFinish();
}
}
/**
* Callback interface for authorization events.
*
*/
public static interface AuthListener {
/**
* Called when a auth flow completes successfully and a valid OAuth
* Token was received.
*
* Executed by the thread that initiated the authentication.
*
* API requests can now be made.
*/
public void onAuthSucceed();
/**
* Called when a login completes unsuccessfully with an error.
*
* Executed by the thread that initiated the authentication.
*/
public void onAuthFail(String error);
}
/**
* Callback interface for logout events.
*
*/
public static interface LogoutListener {
/**
* Called when logout begins, before session is invalidated.
* Last chance to make an API call.
*
* Executed by the thread that initiated the logout.
*/
public void onLogoutBegin();
/**
* Called when the session information has been cleared.
* UI should be updated to reflect logged-out state.
*
* Executed by the thread that initiated the logout.
*/
public void onLogoutFinish();
}
}

@ -1,53 +0,0 @@
/*
* Copyright 2010 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.android;
import com.facebook.android.Facebook;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class SessionStore {
private static final String TOKEN = "access_token";
private static final String EXPIRES = "expires_in";
private static final String KEY = "facebook-session";
public static boolean save(Facebook session, Context context) {
Editor editor =
context.getSharedPreferences(KEY, Context.MODE_PRIVATE).edit();
editor.putString(TOKEN, session.getAccessToken());
editor.putLong(EXPIRES, session.getAccessExpires());
return editor.commit();
}
public static boolean restore(Facebook session, Context context) {
SharedPreferences savedSession =
context.getSharedPreferences(KEY, Context.MODE_PRIVATE);
session.setAccessToken(savedSession.getString(TOKEN, null));
session.setAccessExpires(savedSession.getLong(EXPIRES, 0));
return session.isSessionValid();
}
public static void clear(Context context) {
Editor editor =
context.getSharedPreferences(KEY, Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();
}
}

@ -1,19 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0" package="com.facebook.stream">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".App"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk android:minSdkVersion="3" />
</manifest>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

@ -1,14 +0,0 @@
#main {
width: 200px;
margin: 50% auto 0 auto;
text-align: center;
}
#welcome {
margin-bottom: 10px;
}
#login_button {
width: 91px;
margin: auto;
}

@ -1,13 +0,0 @@
<html>
<head>
<link rel="stylesheet" href="file:///android_asset/login.css" type="text/css"/>
</head>
<body>
<div id="main">
<div id="welcome">Welcome to Stream</div>
<div id="login_button">
<a onclick="app.login()"><img src="file:///android_asset/login_button.png" width="90" height="31"/></a>
</div>
</div>
</body>
</html>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

@ -1,118 +0,0 @@
a {
color: #00f;
}
a:visited {
color: #00f;
}
.hidden {
display: none;
}
.clear {
clear: both
}
#header {
float: right;
}
input {
width: 80%;
height: 28px;
border: #666 solid 1px;
margin: 1px 3px 0 0;
float: left;
}
#status_box {
margin: 5px 0;
}
#status_input {
color: #666;
float: left;
}
.profile_pic_container {
float: left;
margin: 0 5px;
}
.profile_pic {
width: 30px;
height: 30px;
}
.attachment {
margin-top: 3px;
}
.title {
margin-bottom: 3px;
}
.caption {
margin-bottom: 3px;
color: #666;
}
.description {
color: #666;
}
.picture {
float: left;
margin-right: 5px;
}
.post {
padding: 10px 0;
border-bottom: #ccc solid 1px;
}
.action_links {
margin: 5px 0;
}
.action_link {
margin-right: 5px;
float: left;
}
.comment {
padding: 5px 0;
margin-bottom: 2px;
background-color: #eee;
min-height: 30px;
}
.comments {
margin-top: 5px;
}
.comment_box {
display: none;
}
.timestamp {
color: #666;
}
.like_icon {
float: left;
top: 3px;
position: relative;
margin-right: 5px;
}
.like_icon img {
width: 16px;
height: 14px;
}
.num_likes {
padding-left: 5px;
}

@ -1,88 +0,0 @@
function $(id) {
return document.getElementById(id);
}
function show(id) {
$(id).style.display = "block";
}
function hide(id) {
$(id).style.display = "none";
}
function onStatusBoxFocus(elt) {
elt.value = '';
elt.style.color = "#000";
show('status_submit');
}
function updateStatus() {
var message = $('status_input').value;
if (message == "") {
return;
}
$('status_input').disabled = true;
$('status_submit').disabled = true;
app.updateStatus(message);
}
function onStatusUpdated(html) {
$('status_input').disabled = false;
$('status_submit').disabled = false;
$('posts').innerHTML = html + $('posts').innerHTML;
}
function like(post_id) {
doLike(post_id, true);
}
function unlike(post_id) {
doLike(post_id, false);
}
function doLike(post_id, val) {
var ids = getLikeLinkIds(post_id, val);
$(ids[0]).disabled = true;
app.like(post_id, val);
}
// called when the api request has succeeded
function onLike(post_id, val) {
var ids = getLikeLinkIds(post_id, val);
$(ids[0]).disabled = false;
hide(ids[0]);
show(ids[1]);
}
function getLikeLinkIds(post_id, val) {
if (val) {
var prefix1 = 'like';
var prefix2 = 'unlike';
} else {
var prefix1 = 'unlike';
var prefix2 = 'like';
}
return [prefix1 + post_id, prefix2 + post_id];
}
function comment(post_id) {
show("comment_box" + post_id);
$("comment_box_input" + post_id).focus();
}
function postComment(post_id) {
var message = $("comment_box_input" + post_id).value;
if (message == "") {
return;
}
$("comment_box" + post_id).disabled = true;
app.postComment(post_id, message);
}
function onComment(post_id, html) {
$("comments" + post_id).innerHTML += html;
$("comment_box" + post_id).disabled = false;
$("comment_box_input" + post_id).value = "";
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 KiB

@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">stream</string>
</resources>

@ -1,70 +0,0 @@
/*
* Copyright 2010 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.stream;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.Intent;
import android.os.Bundle;
import com.facebook.android.Facebook;
/**
* This class implements the application's main Activity.
*
* @author yariv
*/
public class App extends Activity {
// This is a demo application ID just to get this demo up and running
// If you modify this to work for your own app, you must use your
// own Facebook Application ID.
// See http://www.facebook.com/developers/createapp.php
public static final String FB_APP_ID = "126642314059639";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (FB_APP_ID == null) {
Builder alertBuilder = new Builder(this);
alertBuilder.setTitle("Warning");
alertBuilder.setMessage("A Facebook Applicaton ID must be " +
"specified before running this example: see App.java");
alertBuilder.create().show();
}
// Initialize the dispatcher
Dispatcher dispatcher = new Dispatcher(this);
dispatcher.addHandler("login", LoginHandler.class);
dispatcher.addHandler("stream", StreamHandler.class);
dispatcher.addHandler("logout", LogoutHandler.class);
// If a session already exists, render the stream page
// immediately. Otherwise, render the login page.
Session session = Session.restore(this);
if (session != null) {
dispatcher.runHandler("stream");
} else {
dispatcher.runHandler("login");
}
}
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
Facebook fb = Session.wakeupForAuthCallback();
fb.authorizeCallback(requestCode, resultCode, data);
}
}

@ -1,67 +0,0 @@
/*
* Copyright 2010 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.stream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
abstract class AsyncRequestListener implements RequestListener {
public void onComplete(String response, final Object state) {
try {
JSONObject obj = Util.parseJson(response);
onComplete(obj, state);
} catch (JSONException e) {
e.printStackTrace();
Log.e("facebook-stream", "JSON Error:" + e.getMessage());
} catch (FacebookError e) {
Log.e("facebook-stream", "Facebook Error:" + e.getMessage());
}
}
public abstract void onComplete(JSONObject obj, final Object state);
public void onFacebookError(FacebookError e, final Object state) {
Log.e("stream", "Facebook Error:" + e.getMessage());
}
public void onFileNotFoundException(FileNotFoundException e,
final Object state) {
Log.e("stream", "Resource not found:" + e.getMessage());
}
public void onIOException(IOException e, final Object state) {
Log.e("stream", "Network Error:" + e.getMessage());
}
public void onMalformedURLException(MalformedURLException e,
final Object state) {
Log.e("stream", "Invalid URL:" + e.getMessage());
}
}

@ -1,192 +0,0 @@
/*
* Copyright 2010 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.stream;
import java.util.HashMap;
import android.app.Activity;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
/**
* Handles the rendering of the WebView instance and the
* mapping of app:// urls to their appropriate Handlers.
*
* @author yariv
*/
public class Dispatcher {
// The WebView instance
private WebView webView;
// The app's main Activity
private Activity activity;
// Contains the webView object
LinearLayout layout;
// Has the webView been rendered?
boolean isWebViewShown;
// Holds mappings between handler names to their classes
// (e.g. "login" -> LoginHandler.class)
HashMap<String, Class> handlers;
public Dispatcher(Activity activity) {
this.activity = activity;
handlers = new HashMap<String, Class>();
layout = new LinearLayout(activity);
activity.addContentView(
layout, new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
isWebViewShown = false;
showWebView();
}
/**
* Adds a handler name to handler class mapping. This should be called
* for each handler when the application starts up.
*
* @param name
* @param clazz
*/
public void addHandler(String name, Class clazz) {
this.handlers.put(name, clazz);
}
/**
* Executes the handler associated with the given name. For example,
* dispatcher.runHandler("login") would render the Login page in the
* WebView instance.
*
* @param name
*/
public void runHandler(String name) {
Class clazz = handlers.get(name);
if (clazz != null) {
try {
Handler handler = (Handler)clazz.newInstance();
handler.setDispatcher(this);
handler.go();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
}
/**
* Show the app's WebView instance.
*/
public void showWebView() {
if (isWebViewShown) {
return;
}
webView = new WebView(activity);
webView.setWebViewClient(new AppWebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
layout.addView(webView,
new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
isWebViewShown = true;
}
/**
* Hide the app's WebView instance. This should be called if the
* WebView instance is visible and the app wants to open another
* WebView instance (e.g. for a Facebook dialog). Android doesn't
* seem to be able to handle more than one WebView instance per
* application.
*/
public void hideWebView() {
layout.removeView(webView);
isWebViewShown = false;
}
/**
* Returns true if the WebView instance is visible.
*/
public boolean isWebViewShown() {
return isWebViewShown;
}
/**
* Loads the html string into the WebView instance.
*
* @param html
*/
public void loadData(String html) {
webView.loadDataWithBaseURL(
"http://nada", html, "text/html", "utf8", "");
}
/**
* Loads a file from the assets directory into the
* WebView instance.
*
* @param file
*/
public void loadFile(String file) {
webView.loadUrl(getAbsoluteUrl(file));
}
/**
* Returns the absolute URL for a local file.
*
* @param file
*/
public static String getAbsoluteUrl(String file) {
return "file:///android_asset/" + file;
}
/**
* Returns the Dispatcher's WebView instance.
*/
public WebView getWebView() {
return webView;
}
/**
* Returns the Dispatcher's Activity
*/
public Activity getActivity() {
return activity;
}
/**
* Enables the mapping of app:// urls to Handlers.
*
* @author yariv
*/
private class AppWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("app://")) {
String handlerName = url.substring(6);
runHandler(handlerName);
return true;
}
return false;
}
}
}

@ -1,76 +0,0 @@
/*
* Copyright 2010 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.stream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import android.app.Activity;
/**
* Helpers for doing basic file IO.
*
* @author yariv
*
*/
public class FileIO {
/**
* Write the data to the file indicate by fileName. The file is created
* if it doesn't exist.
*
* @param activity
* @param data
* @param fileName
* @throws IOException
*/
public static void write(
Activity activity, String data, String fileName)
throws IOException {
FileOutputStream fo = activity.openFileOutput(fileName, 0);
BufferedWriter bf = new BufferedWriter(new FileWriter(fo.getFD()));
bf.write(data);
bf.flush();
bf.close();
}
/**
* Read the contents of the file indicated by fileName
*
* @param activity
* @param fileName
* @return the contents
* @throws IOException
*/
public static String read(Activity activity, String fileName)
throws IOException {
FileInputStream is = activity.openFileInput(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
while (br.ready()) {
String line = br.readLine();
sb.append(line);
}
String data = sb.toString();
return data;
}
}

@ -1,70 +0,0 @@
/*
* Copyright 2010 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.stream;
import android.app.Activity;
import android.webkit.WebView;
/**
* An abstract superclass for handlers. Handlers are similar to
* controllers in traditional web apps. Each page has a handler
* that is responsible for rendering the page.
*
* @author yariv
*/
public abstract class Handler {
// The app's dispatcher.
protected Dispatcher dispatcher;
/**
* The dispatcher calls this method when the Handler
* is expected to render its page.
*/
public abstract void go();
/**
* A setter for the dispatcher.
*
* @param dispatcher
*/
public void setDispatcher(Dispatcher dispatcher) {
this.dispatcher = dispatcher;
}
/**
* Returns the dispatcher.
*/
public Dispatcher getDispatcher() {
return dispatcher;
}
/**
* Returns the dispatcher's WebView
*/
public WebView getWebView() {
return dispatcher.getWebView();
}
/**
* Returns the dispatcher's Activity
*/
public Activity getActivity() {
return dispatcher.getActivity();
}
}

@ -1,126 +0,0 @@
/*
* Copyright 2010 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.stream;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
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;
/**
* A handler for the login page.
*
* @author yariv
*/
public class LoginHandler extends Handler {
// The permissions that the app should request from the user
// when the user authorizes the app.
private static String[] PERMISSIONS =
new String[] { "offline_access", "read_stream", "publish_stream" };
/**
* Render the Login page.
*/
public void go() {
dispatcher.getWebView().addJavascriptInterface(
new JsHandler(), "app");
dispatcher.loadFile("login.html");
}
/**
* Contains functions that are exported to the Javascript context
* in Login.html
*
* @author yariv
*/
private class JsHandler {
/**
* Opens the Facebook login dialog.
*/
public void login() {
final Activity activity = LoginHandler.this.getActivity();
activity.runOnUiThread(new Runnable() {
public void run() {
// We need to temporarily remove the app's WebView
// instance because Android apparently doesn't support
// multiple WebView instances in the same app.
dispatcher.hideWebView();
final Facebook fb = new Facebook(App.FB_APP_ID);
Session.waitForAuthCallback(fb);
fb.authorize(getActivity(), PERMISSIONS,
new AppLoginListener(fb));
}
});
}
private class AppLoginListener implements DialogListener {
private Facebook fb;
public AppLoginListener(Facebook fb) {
this.fb = fb;
}
public void onCancel() {
Log.d("app", "login canceled");
}
public void onComplete(Bundle values) {
/**
* We request the user's info so we can cache it locally and
* use it to render the new html snippets
* when the user updates her status or comments on a post.
*/
new AsyncFacebookRunner(fb).request("/me",
new AsyncRequestListener() {
public void onComplete(JSONObject obj, final Object state) {
// save the session data
String uid = obj.optString("id");
String name = obj.optString("name");
new Session(fb, uid, name).save(getActivity());
// render the Stream page in the UI thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
dispatcher.showWebView();
dispatcher.runHandler("stream");
}
});
}
}, null);
}
public void onError(DialogError e) {
Log.d("app", "dialog error: " + e);
}
public void onFacebookError(FacebookError e) {
Log.d("app", "facebook error: " + e);
}
}
}
}

@ -1,78 +0,0 @@
/*
* Copyright 2010 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.stream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import android.util.Log;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
/**
* A handler for the logout link. This handler doesn't render
* its own page. After logging out it redirects the user
* to the login handler.
*
* @author yariv
*/
public class LogoutHandler extends Handler {
/**
* Called by the dispatcher when the user clicks 'logout'.
*/
public void go() {
Facebook fb = Session.restore(getActivity()).getFb();
// clear the local session data
Session.clearSavedSession(getActivity());
new AsyncFacebookRunner(fb).logout(getActivity(),
new RequestListener() {
public void onComplete(String response, final Object state) {
dispatcher.runHandler("login");
}
public void onFileNotFoundException(FileNotFoundException error,
final Object state) {
Log.e("app", error.toString());
dispatcher.runHandler("login");
}
public void onIOException(IOException error, final Object state) {
Log.e("app", error.toString());
dispatcher.runHandler("login");
}
public void onMalformedURLException(MalformedURLException error,
final Object state) {
Log.e("app", error.toString());
dispatcher.runHandler("login");
}
public void onFacebookError(FacebookError error,
final Object state) {
Log.e("app", error.toString());
dispatcher.runHandler("login");
}
});
}
}

@ -1,174 +0,0 @@
/*
* Copyright 2010 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.stream;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import com.facebook.android.Facebook;
/**
* A utility class for storing and retrieving Facebook session data.
*
* @author yariv
*/
public class Session {
private static final String TOKEN = "access_token";
private static final String EXPIRES = "expires_in";
private static final String KEY = "facebook-session";
private static final String UID = "uid";
private static final String NAME = "name";
private static final String APP_ID = "app_id";
private static Session singleton;
private static Facebook fbLoggingIn;
// The Facebook object
private Facebook fb;
// The user id of the logged in user
private String uid;
// The user name of the logged in user
private String name;
/**
* Constructor
*
* @param fb
* @param uid
* @param name
*/
public Session(Facebook fb, String uid, String name) {
this.fb = fb;
this.uid = uid;
this.name = name;
}
/**
* Returns the Facebook object
*/
public Facebook getFb() {
return fb;
}
/**
* Returns the session user's id
*/
public String getUid() {
return uid;
}
/**
* Returns the session user's name
*/
public String getName() {
return name;
}
/**
* Stores the session data on disk.
*
* @param context
* @return
*/
public boolean save(Context context) {
Editor editor =
context.getSharedPreferences(KEY, Context.MODE_PRIVATE).edit();
editor.putString(TOKEN, fb.getAccessToken());
editor.putLong(EXPIRES, fb.getAccessExpires());
editor.putString(UID, uid);
editor.putString(NAME, name);
editor.putString(APP_ID, fb.getAppId());
if (editor.commit()) {
singleton = this;
return true;
}
return false;
}
/**
* Loads the session data from disk.
*
* @param context
* @return
*/
public static Session restore(Context context) {
if (singleton != null) {
if (singleton.getFb().isSessionValid()) {
return singleton;
} else {
return null;
}
}
SharedPreferences prefs =
context.getSharedPreferences(KEY, Context.MODE_PRIVATE);
String appId = prefs.getString(APP_ID, null);
if (appId == null) {
return null;
}
Facebook fb = new Facebook(appId);
fb.setAccessToken(prefs.getString(TOKEN, null));
fb.setAccessExpires(prefs.getLong(EXPIRES, 0));
String uid = prefs.getString(UID, null);
String name = prefs.getString(NAME, null);
if (!fb.isSessionValid() || uid == null || name == null) {
return null;
}
Session session = new Session(fb, uid, name);
singleton = session;
return session;
}
/**
* Clears the saved session data.
*
* @param context
*/
public static void clearSavedSession(Context context) {
Editor editor =
context.getSharedPreferences(KEY, Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();
singleton = null;
}
/**
* Freezes a Facebook object while it's waiting for an auth callback.
*/
public static void waitForAuthCallback(Facebook fb) {
fbLoggingIn = fb;
}
/**
* Returns a Facebook object that's been waiting for an auth callback.
*/
public static Facebook wakeupForAuthCallback() {
Facebook fb = fbLoggingIn;
fbLoggingIn = null;
return fb;
}
}

@ -1,118 +0,0 @@
/*
* Copyright 2010 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.stream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
/**
* A handler for the stream page. It's responsible for
* fetching the stream data from the API and storing it
* in a local file based cache. It uses the helper class
* StreamRenderer to render the stream.
*
* @author yariv
*/
public class StreamHandler extends Handler {
private static final String CACHE_FILE = "cache.txt";
/**
* Called by the dispatcher to render the stream page.
*/
public void go() {
dispatcher.getWebView().addJavascriptInterface(
new StreamJsHandler(this), "app");
// first try to load the cached data
try {
String cached = FileIO.read(getActivity(), CACHE_FILE);
if (cached != null) {
JSONObject obj = new JSONObject(cached);
dispatcher.loadData(StreamRenderer.render(obj));
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
Facebook fb = Session.restore(getActivity()).getFb();
new AsyncFacebookRunner(fb).request("me/home",
new StreamRequestListener());
}
public class StreamRequestListener implements RequestListener {
public void onComplete(String response, final Object state) {
try {
JSONObject obj = Util.parseJson(response);
// try to cache the result
try {
FileIO.write(getActivity(), response, CACHE_FILE);
} catch (IOException e) {
e.printStackTrace();
}
// Convert the result into an HTML string and then load it
// into the WebView in the UI thread.
final String html = StreamRenderer.render(obj);
getActivity().runOnUiThread(new Runnable() {
public void run() {
dispatcher.loadData(html);
}
});
} catch (JSONException e) {
Log.e("stream", "JSON Error:" + e.getMessage());
} catch (FacebookError e) {
Log.e("stream", "Facebook Error:" + e.getMessage());
}
}
public void onFacebookError(FacebookError e, final Object state) {
Log.e("stream", "Facebook Error:" + e.getMessage());
}
public void onFileNotFoundException(FileNotFoundException e,
final Object state) {
Log.e("stream", "Resource not found:" + e.getMessage());
}
public void onIOException(IOException e, final Object state) {
Log.e("stream", "Network Error:" + e.getMessage());
}
public void onMalformedURLException(MalformedURLException e,
final Object state) {
Log.e("stream", "Invalid URL:" + e.getMessage());
}
}
}

@ -1,205 +0,0 @@
/*
* Copyright 2010 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.stream;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.Facebook;
/**
* Implements functions that can be called from Javascript in the
* stream page.
*
* @author yariv
*/
class StreamJsHandler {
// The handler for the Stream page
private final StreamHandler streamHandler;
/**
* @param streamHandler
*/
StreamJsHandler(StreamHandler streamHandler) {
this.streamHandler = streamHandler;
}
/**
* Returns the Facebook object.
*/
private AsyncFacebookRunner getFb() {
Facebook fb = Session.restore(streamHandler.getActivity()).getFb();
return new AsyncFacebookRunner(fb);
}
/**
* Update the status and render the resulting status at the
* top of the stream.
*
* @param message
*/
public void updateStatus(final String message) {
AsyncFacebookRunner fb = getFb();
Bundle params = new Bundle();
params.putString("message", message);
fb.request("me/feed", params, "POST", new AsyncRequestListener() {
public void onComplete(JSONObject obj, final Object state) {
String html;
try {
html = renderStatus(obj, message);
html = html.replace("'", "\\\'");
callJs("onStatusUpdated('" + html + "');");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, null);
}
/**
* Renders the html for the new status.
*
* @param response
* @param message
* @return
* @throws JSONException
*/
private String renderStatus(JSONObject response, String message)
throws JSONException {
String postId = response.getString("id");
JSONObject post = new JSONObject();
post.put("id", postId);
post.put("message", message);
JSONObject from = createAuthorObj();
post.put("from", from);
JSONArray actions = new JSONArray();
JSONObject like = new JSONObject();
like.put("name", "Like");
actions.put(like);
JSONObject comment = new JSONObject();
comment.put("name", "Comment");
actions.put(comment);
post.put("actions", actions);
SimpleDateFormat format = StreamRenderer.getDateFormat();
String timestamp = format.format(new Date());
post.put("created_time", timestamp);
String html = StreamRenderer.renderSinglePost(post);
return html;
}
/**
* Like or unlike a post
*
* @param post_id
* @param val if the action should be a like (true) or an unlike (false)
*/
public void like(final String post_id, final boolean val) {
Bundle params = new Bundle();
if (!val) {
params.putString("method", "delete");
}
getFb().request(post_id + "/likes", new Bundle(), "POST",
new AsyncRequestListener() {
public void onComplete(JSONObject response, final Object state) {
callJs("javascript:onLike('" + post_id + "'," + val + ")");
}
}, null);
}
public void postComment(final String post_id, final String message) {
Bundle params = new Bundle();
params.putString("message", message);
getFb().request(post_id + "/comments", params, "POST",
new AsyncRequestListener() {
public void onComplete(JSONObject response, final Object state) {
try {
String html = renderComment(response, message);
html = html.replace("'", "\\'");
callJs("onComment('" + post_id + "','" + html + "');");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, null);
}
/**
* Renders the html string for a new comment.
*
* @param response
* @param message
* @return
* @throws JSONException
*/
private String renderComment(JSONObject response, String message)
throws JSONException {
JSONObject comment = new JSONObject();
String commentId = response.getString("id");
comment.put("id", commentId);
comment.put("from", createAuthorObj());
comment.put("message", message);
String html = StreamRenderer.renderSingleComment(comment);
return html;
}
/**
* Executes javascript code inside WebKit.
*
* @param js
*/
private void callJs(String js) {
streamHandler.getWebView().loadUrl("javascript:" + js);
}
/**
* Creates a JSONObject for the post or comment author.
*
* @return
* @throws JSONException
*/
private JSONObject createAuthorObj() throws JSONException {
Session session = Session.restore(streamHandler.getActivity());
JSONObject from = new JSONObject();
from.put("id", session.getUid());
from.put("name", session.getName());
return from;
}
}

@ -1,538 +0,0 @@
/*
* Copyright 2010 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.stream;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
/**
* Contains logic for converting a JSONObject obtained from
* querying /me/home to a HTML string that can be rendered
* in WebKit.
*
* @author yariv
*/
class StreamRenderer {
private StringBuilder sb;
/**
* The main function for rendering the stream JSONObject.
*
* @param data
* @return
*/
public static String render(JSONObject data) {
StreamRenderer renderer = new StreamRenderer();
return renderer.doRender(data);
}
/**
* Renders the HTML for a single post.
*
* @param post
* @return
* @throws JSONException
*/
public static String renderSinglePost(JSONObject post)
throws JSONException {
StreamRenderer renderer = new StreamRenderer();
renderer.renderPost(post);
return renderer.getResult();
}
/**
* Renders the HTML for a single comment.
*
* @param comment
* @return
*/
public static String renderSingleComment(JSONObject comment) {
StreamRenderer renderer = new StreamRenderer();
renderer.renderComment(comment);
return renderer.getResult();
}
private StreamRenderer() {
this.sb = new StringBuilder();
}
/**
* Returns a SimpleDateFormat object we use for
* parsing and rendering timestamps.
*
* @return
*/
public static SimpleDateFormat getDateFormat() {
return new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
}
/**
* Returns the result html.
*
* @return
*/
private String getResult() {
return sb.toString();
}
private String doRender(JSONObject data) {
try {
JSONArray posts = data.getJSONArray("data");
String[] chunks = {
"<html><head>",
"<link rel=\"stylesheet\" " +
"href=\"file:///android_asset/stream.css\" type=\"text/css\">",
"<script src=\"file:///android_asset/stream.js\"></script>",
"</head>",
"<body>",
"<div id=\"header\">"
};
append(chunks);
renderLink("app://logout", "logout");
renderStatusBox();
append("<div id=\"posts\">");
for (int i = 0; i < posts.length(); i++) {
renderPost(posts.getJSONObject(i));
}
append("</div></body></html>");
return getResult();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
/**
* Renders the "what's on your mind?" box and the Share button.
*/
private void renderStatusBox() {
String[] chunks = new String[] {
"</div><div class=\"clear\"></div>",
"<div id=\"status_box\">",
"<input id=\"status_input\" value=\" What's on your mind?\"",
" onfocus=\"onStatusBoxFocus(this);\"/>",
"<button id=\"status_submit\" class=\"hidden\" " +
"onclick=\"updateStatus();\">Share</button>",
"<div class=\"clear\"></div>",
"</div>"
};
append(chunks);
}
/**
* Renders a single post
*
* @param post
* @throws JSONException
*/
private void renderPost(JSONObject post) throws JSONException {
append("<div class=\"post\">");
renderFrom(post);
renderTo(post);
renderMessage(post);
renderAttachment(post);
renderActionLinks(post);
renderLikes(post);
renderComments(post);
renderCommentBox(post);
append("</div>");
}
/**
* Renders the author's name
*
* @param post
* @throws JSONException
*/
private void renderFrom(JSONObject post) throws JSONException {
JSONObject from = post.getJSONObject("from");
String fromName = from.getString("name");
String fromId = from.getString("id");
renderAuthor(fromId, fromName);
}
/**
* If it's a wall post on a friend's fall, renders
* the recipient's name preceded by a '>'.
*
* @param post
* @throws JSONException
*/
private void renderTo(JSONObject post) throws JSONException {
JSONObject to = post.optJSONObject("to");
if (to != null) {
JSONObject toData = to.getJSONArray("data").getJSONObject(0);
String toName = toData.getString("name");
String toId = toData.getString("id");
append(" > ");
renderProfileLink(toId, toName);
}
}
/**
* Renders a link to a user.
*
* @param id
* @param name
*/
private void renderProfileLink(String id, String name) {
renderLink(getProfileUrl(id), name);
}
private String getProfileUrl(String id) {
return "http://touch.facebook.com/#/profile.php?id=" + id;
}
/**
* Renders the author pic and name.
*
* @param id
* @param name
*/
private void renderAuthor(String id, String name) {
String[] chunks = {
"<div class=\"profile_pic_container\">",
"<a href=\"", getProfileUrl(id),
"\"><img class=\"profile_pic\" src=\"http://graph.facebook.com/",
id, "/picture\"/></a>",
"</div>"
};
append(chunks);
renderProfileLink(id, name);
}
/**
* Renders the post message.
*
* @param post
*/
private void renderMessage(JSONObject post) {
String message = post.optString("message");
String[] chunks = {
"&nbsp;<span class=\"msg\">", message, "</span>",
"<div class=\"clear\"></div>"
};
append(chunks);
}
/**
* Renders the attachment.
*
* @param post
*/
private void renderAttachment(JSONObject post) {
String name = post.optString("name");
String link = post.optString("link");
String picture = post.optString("picture");
String source = post.optString("source"); // for videos
String caption = post.optString("caption");
String description = post.optString("description");
String[] fields = new String[] {
name, link, picture, source, caption, description
};
boolean hasAttachment = false;
for (String field : fields) {
if (field.length() != 0) {
hasAttachment = true;
break;
}
}
if (!hasAttachment) {
return;
}
append("<div class=\"attachment\">");
if (name != "") {
append("<div class=\"title\">");
if (link != null) {
renderLink(link, name);
} else {
append(name);
}
append("</div>");
}
if (caption != "") {
append("<div class=\"caption\">" + caption + "</div>");
}
if (picture != "") {
append("<div class=\"picture\">");
String img = "<img src=\"" + picture + "\"/>";
if (link != "") {
renderLink(link, img);
} else {
append(img);
}
append("</div>");
}
if (description != "") {
append("<div class=\"description\">" + description + "</div>");
}
append("<div class=\"clear\"></div></div>");
}
/**
* Renders an anchor tag
*
* @param href
* @param text
*/
private void renderLink(String href, String text) {
append(new String[] {
"<a href=\"",
href,
"\">",
text,
"</a>"
});
}
/**
* Renders the posts' action links.
*
* @param post
*/
private void renderActionLinks(JSONObject post) {
HashSet<String> actions = getActions(post);
append("<div class=\"action_links\">");
append("<div class=\"action_link\">");
renderTimeStamp(post);
append("</div>");
String post_id = post.optString("id");
if (actions.contains("Comment")) {
renderActionLink(post_id, "Comment", "comment");
}
boolean canLike = actions.contains("Like");
renderActionLink(post_id, "Like", "like", canLike);
renderActionLink(post_id, "Unlike", "unlike", !canLike);
append("<div class=\"clear\"></div></div>");
}
/**
* Renders a single visible action link.
*
* @param post_id
* @param title
* @param func
*/
private void renderActionLink(String post_id, String title, String func) {
renderActionLink(post_id, title, func, true);
}
/**
* Renders an action link with optional visibility.
*
* @param post_id
* @param title
* @param func
* @param visible
*/
private void renderActionLink(String post_id, String title, String func,
boolean visible) {
String extraClass = visible ? "" : "hidden";
String[] chunks = new String[] {
"<div id=\"", func, post_id, "\" class=\"action_link ",
extraClass, "\">", "<a href=\"#\" onclick=\"",func, "('",
post_id, "'); return false;\">", title, "</a></div>"
};
append(chunks);
}
/**
* Renders the post's timestamp.
*
* @param post
*/
private void renderTimeStamp(JSONObject post) {
String dateStr = post.optString("created_time");
SimpleDateFormat formatter = getDateFormat();
ParsePosition pos = new ParsePosition(0);
long then = formatter.parse(dateStr, pos).getTime();
long now = new Date().getTime();
long seconds = (now - then)/1000;
long minutes = seconds/60;
long hours = minutes/60;
long days = hours/24;
String friendly = null;
long num = 0;
if (days > 0) {
num = days;
friendly = days + " day";
} else if (hours > 0) {
num = hours;
friendly = hours + " hour";
} else if (minutes > 0) {
num = minutes;
friendly = minutes + " minute";
} else {
num = seconds;
friendly = seconds + " second";
}
if (num > 1) {
friendly += "s";
}
String[] chunks = new String[] {
"<div class=\"timestamp\">",
friendly,
" ago",
"</div>"
};
append(chunks);
}
/**
* Returns the available actions for the post.
*
* @param post
* @return
*/
private HashSet<String> getActions(JSONObject post) {
HashSet<String> actionsSet = new HashSet<String>();
JSONArray actions = post.optJSONArray("actions");
if (actions != null) {
for (int j = 0; j < actions.length(); j++) {
JSONObject action = actions.optJSONObject(j);
String actionName = action.optString("name");
actionsSet.add(actionName);
}
}
return actionsSet;
}
/**
* Renders the 'x people like this' text,
*
* @param post
*/
private void renderLikes(JSONObject post) {
int numLikes = post.optInt("likes", 0);
if (numLikes > 0) {
String desc = numLikes == 1 ?
"person likes this" :
"people like this";
String[] chunks = new String[] {
"<div class=\"like_icon\">",
"<img src=\"file:///android_asset/like_icon.png\"/>",
"</div>",
"<div class=\"num_likes\">",
new Integer(numLikes).toString(),
" ",
desc,
"</div>"
};
append(chunks);
}
}
/**
* Renders the post's comments.
*
* @param post
* @throws JSONException
*/
private void renderComments(JSONObject post) throws JSONException {
append("<div class=\"comments\" id=\"comments" + post.optString("id")
+ "\">");
JSONObject comments = post.optJSONObject("comments");
if (comments != null) {
JSONArray data = comments.optJSONArray("data");
if (data != null) {
for (int j = 0; j < data.length(); j++) {
JSONObject comment = data.getJSONObject(j);
renderComment(comment);
}
}
}
append("</div>");
}
/**
* Renders an individual comment.
*
* @param comment
*/
private void renderComment(JSONObject comment) {
JSONObject from = comment.optJSONObject("from");
if (from == null) {
Log.w("StreamRenderer",
"Comment missing from field: " + comment.toString());
} else {
String authorId = from.optString("id");
String authorName = from.optString("name");
renderAuthor(authorId, authorName);
}
String message = comment.optString("message");
append("<div class=\"comment\">");
String[] chunks = {
"&nbsp;",
message,
"</div>"
};
append(chunks);
}
/**
* Renders the new comment input box.
*
* @param post
*/
private void renderCommentBox(JSONObject post) {
String id = post.optString("id");
String[] chunks = new String[] {
"<div class=\"comment_box\" id=\"comment_box", id, "\">",
"<input id=\"comment_box_input", id, "\"/>",
"<button onclick=\"postComment('", id , "');\">Post</button>",
"<div class=\"clear\"></div>",
"</div>"
};
append(chunks);
}
private void append(String str) {
sb.append(str);
}
private void append(String[] chunks) {
for (String chunk : chunks) {
sb.append(chunk);
}
}
}

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<projectDescription> <projectDescription>
<name>facebook</name> <name>FacebookSDK</name>
<comment></comment> <comment></comment>
<projects> <projects>
</projects> </projects>

@ -18,4 +18,5 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.facebook.android"> package="com.facebook.android">
<application/> <application/>
<uses-sdk android:minSdkVersion="8" />
</manifest> </manifest>

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.facebook.sdk"
android:versionCode="1"
android:versionName="1.0">
<application android:label="@string/app_name" android:icon="@drawable/ic_launcher">
<activity android:name="StatusActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<component>
<exclude-output/>
<contentEntry url="file://$MODULE_DIR$"/>
</component>

@ -0,0 +1,17 @@
# This file is used to override default values used by the Ant build system.
#
# This file must be checked into Version Control Systems, as it is
# integral to the build system of your project.
# This file is only used by the Ant script.
# You can use this to override default values such as
# 'source.dir' for the location of your java source folder and
# 'out.dir' for the location of your output folder.
# You can also use it define how the release builds are signed by declaring
# the following properties:
# 'key.store' for the location of your keystore and
# 'key.alias' for the name of the key to use.
# The password will be asked during the build when you use the 'release' target.

@ -0,0 +1,83 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="FacebookSdk" default="help">
<!-- The local.properties file is created and updated by the 'android' tool.
It contains the path to the SDK. It should *NOT* be checked into
Version Control Systems. -->
<property file="local.properties" />
<!-- The ant.properties file can be created by you. It is only edited by the
'android' tool to add properties to it.
This is the place to change some Ant specific build properties.
Here are some properties you may want to change/update:
source.dir
The name of the source directory. Default is 'src'.
out.dir
The name of the output directory. Default is 'bin'.
For other overridable properties, look at the beginning of the rules
files in the SDK, at tools/ant/build.xml
Properties related to the SDK location or the project target should
be updated using the 'android' tool with the 'update' action.
This file is an integral part of the build system for your
application and should be checked into Version Control Systems.
-->
<property file="ant.properties" />
<!-- The project.properties file is created and updated by the 'android'
tool, as well as ADT.
This contains project specific properties such as project target, and library
dependencies. Lower level build properties are stored in ant.properties
(or in .classpath for Eclipse projects).
This file is an integral part of the build system for your
application and should be checked into Version Control Systems. -->
<loadproperties srcFile="project.properties" />
<!-- quick check on sdk.dir -->
<fail
message="sdk.dir is missing. Make sure to generate local.properties using 'android update project' or to inject it through an env var"
unless="sdk.dir"
/>
<!--
Import per project custom build rules if present at the root of the project.
This is the place to put custom intermediary targets such as:
-pre-build
-pre-compile
-post-compile (This is typically used for code obfuscation.
Compiled code location: ${out.classes.absolute.dir}
If this is not done in place, override ${out.dex.input.absolute.dir})
-post-package
-post-build
-pre-clean
-->
<import file="custom_rules.xml" optional="true" />
<!-- Import the actual build file.
To customize existing targets, there are two options:
- Customize only one target:
- copy/paste the target into this file, *before* the
<import> task.
- customize it to your needs.
- Customize the whole content of build.xml
- copy/paste the content of the rules files (minus the top node)
into this file, replacing the <import> task.
- customize to your needs.
***********************
****** IMPORTANT ******
***********************
In all cases you must update the value of version-tag below to read 'custom' instead of an integer,
in order to avoid having your file be overridden by tools such as "android update project"
-->
<!-- version-tag: 1 -->
<import file="${sdk.dir}/tools/ant/build.xml" />
</project>

@ -0,0 +1,20 @@
# To enable ProGuard in your project, edit project.properties
# to define the proguard.config property as described in that file.
#
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in ${sdk.dir}/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the ProGuard
# include property in project.properties.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

@ -0,0 +1,15 @@
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system edit
# "ant.properties", and override values to adapt the script to your
# project structure.
#
# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
# Project target.
target=android-8

@ -0,0 +1,29 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright 2012 Facebook
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SDK Unit Tests"
/>
</LinearLayout>

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright 2012 Facebook
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<resources>
<string name="app_name">StatusActivity</string>
</resources>

@ -0,0 +1,31 @@
/**
* Copyright 2012 Facebook
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.sdk;
import android.app.Activity;
import android.os.Bundle;
public class StatusActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<component>
<exclude-output/>
<contentEntry url="file://$MODULE_DIR$"/>
</component>

@ -0,0 +1,2 @@
jar.libs.dir=../lib
java.compilerargs=-Xlint -Werror

@ -4,7 +4,7 @@
<!-- The local.properties file is created and updated by the 'android' tool. <!-- The local.properties file is created and updated by the 'android' tool.
It contains the path to the SDK. It should *NOT* be checked into It contains the path to the SDK. It should *NOT* be checked into
Version Control Systems. --> Version Control Systems. -->
<loadproperties srcFile="local.properties" /> <property file="local.properties" />
<!-- The ant.properties file can be created by you. It is only edited by the <!-- The ant.properties file can be created by you. It is only edited by the
'android' tool to add properties to it. 'android' tool to add properties to it.
@ -41,25 +41,23 @@
<!-- quick check on sdk.dir --> <!-- quick check on sdk.dir -->
<fail <fail
message="sdk.dir is missing. Make sure to generate local.properties using 'android update project'" message="sdk.dir is missing. Make sure to generate local.properties using 'android update project' or to inject it through an env var"
unless="sdk.dir" unless="sdk.dir"
/> />
<!-- extension targets. Uncomment the ones where you want to do custom work
in between standard targets -->
<!-- <!--
<target name="-pre-build"> Import per project custom build rules if present at the root of the project.
</target> This is the place to put custom intermediary targets such as:
<target name="-pre-compile"> -pre-build
</target> -pre-compile
-post-compile (This is typically used for code obfuscation.
/* This is typically used for code obfuscation.
Compiled code location: ${out.classes.absolute.dir} Compiled code location: ${out.classes.absolute.dir}
If this is not done in place, override ${out.dex.input.absolute.dir} */ If this is not done in place, override ${out.dex.input.absolute.dir})
<target name="-post-compile"> -post-package
</target> -post-build
-pre-clean
--> -->
<import file="custom_rules.xml" optional="true" />
<!-- Import the actual build file. <!-- Import the actual build file.

@ -1,12 +0,0 @@
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system use,
# "build.properties", and override values to adapt the script to your
# project structure.
android.library=true
# Project target.
target=android-3

@ -1,40 +0,0 @@
-optimizationpasses 5
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontpreverify
-verbose
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*
-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference
-keep public class com.android.vending.licensing.ILicensingService
-keepclasseswithmembernames class * {
native <methods>;
}
-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet);
}
-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet, int);
}
-keepclassmembers class * extends android.app.Activity {
public void *(android.view.View);
}
-keepclassmembers enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}
-keep class * implements android.os.Parcelable {
public static final android.os.Parcelable$Creator *;
}

@ -3,10 +3,14 @@
# #
# This file must be checked in Version Control Systems. # This file must be checked in Version Control Systems.
# #
# To customize properties used by the Ant build system use, # To customize properties used by the Ant build system edit
# "ant.properties", and override values to adapt the script to your # "ant.properties", and override values to adapt the script to your
# project structure. # project structure.
#
# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
android.library=true android.library=true
# Project target. # Project target.
target=android-14 target=android-14
android.library.reference.1=../../actionbarsherlock/library

Binary file not shown.

After

Width:  |  Height:  |  Size: 624 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 520 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 385 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.7 KiB

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

Before

Width:  |  Height:  |  Size: 3.7 KiB

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 841 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 714 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 495 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright 2012 Facebook
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="@drawable/com_facebook_button_check_on" />
<item android:drawable="@drawable/com_facebook_button_check_off" />
</selector>

Binary file not shown.

After

Width:  |  Height:  |  Size: 549 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 733 B

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save