Android/Facebook : Insufficient priviledges when using Api - android

On my main activity, I have the following code:
FacebookSdk.sdkInitialize(getApplicationContext());
I also added a button to create a post on my Facebook timeline:
Button b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
ShareLinkContent content = new ShareLinkContent.Builder()
.setContentUrl(Uri.parse("https://developers.facebook.com"))
.build();
ShareApi.share(content, new FacebookCallback<Sharer.Result>() {
#Override
public void onSuccess(Result arg0) {
// TODO Auto-generated method stub
}
#Override
public void onError(FacebookException arg0) {
// TODO Auto-generated method stub
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
});
}
When I run my app on my smartphone, and click the button, I always get the following message (onError callback):
Insufficient permissions for sharing content via Api.
I have configured com.facebook.app.FacebookContentProvider, com.facebook.sdk.ApplicationId, com.facebook.FacebookActivity in Manifest file. And also have registered my app on facebook.
What is missing, please? Should I add a facebook Login button on my app?

I have discovered that this error occurs when AccessToken.getCurrentAccessToken() returns null. So I must authenticate to Facebook explicitly before using the ShareAPI.
I saw it in Facebook's source code available at http://android-education-project.googlecode.com/svn/trunk/facebook_4_0_0/src/com/facebook/share/ShareApi.java:
/**
* Share the content.
*
* #param callback the callback to call once the share is complete.
*/
public void share(FacebookCallback<Sharer.Result> callback) {
if (!this.canShare()) {
ShareInternalUtility.invokeCallbackWithError(
callback, "Insufficient permissions for sharing content via Api.");
return;
}
final ShareContent shareContent = this.getShareContent();
// Validate the share content
try {
ShareContentValidation.validateForApiShare(shareContent);
} catch (FacebookException ex) {
ShareInternalUtility.invokeCallbackWithException(callback, ex);
return;
}
if (shareContent instanceof ShareLinkContent) {
this.shareLinkContent((ShareLinkContent) shareContent, callback);
} else if (shareContent instanceof SharePhotoContent) {
this.sharePhotoContent((SharePhotoContent) shareContent, callback);
} else if (shareContent instanceof ShareVideoContent) {
this.shareVideoContent((ShareVideoContent) shareContent, callback);
} else if (shareContent instanceof ShareOpenGraphContent) {
this.shareOpenGraphContent((ShareOpenGraphContent) shareContent, callback);
}
}
/**
* Returns true if the current access token has the publish_actions permission.
*
* #return true if the current access token has the publish_actions permission, false otherwise.
*/
public boolean canShare() {
if (this.getShareContent() == null) {
return false;
}
final AccessToken accessToken = AccessToken.getCurrentAccessToken();
if (accessToken == null) {
return false;
}
final Set<String> permissions = accessToken.getPermissions();
if (permissions == null) {
return false;
}
return (permissions.contains("publish_actions"));
}

Related

FB SDK (4.5.1) login : Connection Failed

I'm using FB SDK version 4.5.1 with eclipse to login to Facebook. Sometimes it login successfully, but some other times it gives me this error message " CONNECTION FAILURE". Is this a problem with my Internet connection or code?
Here is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
Log.d(TAG,"Fb initialzed");
callbackManager = CallbackManager.Factory.create();
//LoginButton loginButton= (LoginButton)findViewById(R.id.fb_login_button);
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult result) {
// TODO Auto-generated method stub
Log.d(TAG,"Login success");
Intent I = new Intent(getApplicationContext(), Games.class);
startActivity(I);
}
private void showAlert() {
new AlertDialog.Builder(GameSurvey.this)
.setTitle(R.string.cancelled)
.setMessage(R.string.permission_not_granted)
.setPositiveButton(R.string.ok, null)
.show();
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
Log.d(TAG,"Login cancelled");
}
#Override
public void onError(FacebookException error) {
// TODO Auto-generated method stub
if(error instanceof FacebookAuthorizationException)
Log.d(TAG,error.toString());
showAlert();
}
});
Log.d(TAG, "here");
setContentView(R.layout.activity_game_survey);
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
updateUI();
// It's possible that we were waiting for Profile to be populated in order to
// post a status update.
}
};
profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture);
}
If you get the error in the error handler callback, then you need to react to it (maybe show a notice to the user and request to try again).
A CONNECTION FAILURE error is self-explanatory. If you can find a specific pattern and you are able to repro this consistently on different networks and clients as well (e.g. web), then this might be a bug. Otherwise, this is unlikely to be a bug.

Android Google Play Services returns invalid token for blogger api

I've been given access to the blogger API, I've confirmed that on my developer console.
I've also written some code to perform oAuth2 with Google Play Services using some of the code below.
String SCOPE ="oauth2:https://www.googleapis.com/auth/blogger";
GoogleAuthUtil.getToken(context, "myEmail#gmail.com", mScope);
It returns a token. As it should.
However, once I try to access the api using the token i get a error.
Unexpected response code 403 for https://www.googleapis.com/blogger/v3/users/self/blogs
Here is my request:
And here is my response:
Here is my BaseActivity.java code that gets the token:
public class BaseActivity extends Activity {
static final int REQUEST_CODE_PICK_ACCOUNT = 1000;
static final int REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR = 1001;
static final int REQUEST_CODE_RECOVER_FROM_AUTH_ERROR = 1002;
private static final String SCOPE ="oauth2:https://www.googleapis.com/auth/blogger";
private String mEmail; // Received from newChooseAccountIntent(); passed to getToken()
public ProgressDialog mDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDialog = new ProgressDialog(this);
login();
}
public void login() {
pickUserAccount();
}
private void pickUserAccount() {
String[] accountTypes = new String[]{"com.google"};
Intent intent = AccountPicker.newChooseAccountIntent(null, null, accountTypes, false, null, null, null, null);
startActivityForResult(intent, REQUEST_CODE_PICK_ACCOUNT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PICK_ACCOUNT) {
// Receiving a result from the AccountPicker
if (resultCode == RESULT_OK) {
mEmail = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
// With the account name acquired, go get the auth token
getToken();
} else if (resultCode == RESULT_CANCELED) {
// The account picker dialog closed without selecting an account.
// Notify users that they must pick an account to proceed.
Toast.makeText(this, "Pick Account", Toast.LENGTH_SHORT).show();
}
} else if ((requestCode == REQUEST_CODE_RECOVER_FROM_AUTH_ERROR ||
requestCode == REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR)
&& resultCode == RESULT_OK) {
// Receiving a result that follows a GoogleAuthException, try auth again
getToken();
}
}
private void getToken() {
if (mEmail == null) {
pickUserAccount();
} else {
if (isDeviceOnline()) {
new getTokenTask(BaseActivity.this, mEmail, SCOPE).execute();
} else {
Toast.makeText(this, "Not online", Toast.LENGTH_LONG).show();
}
}
}
/**
* This method is a hook for background threads and async tasks that need to
* provide the user a response UI when an exception occurs.
*/
public void handleException(final Exception e) {
// Because this call comes from the AsyncTask, we must ensure that the following
// code instead executes on the UI thread.
runOnUiThread(new Runnable() {
#Override
public void run() {
if (e instanceof GooglePlayServicesAvailabilityException) {
// The Google Play services APK is old, disabled, or not present.
// Show a dialog created by Google Play services that allows
// the user to update the APK
int statusCode = ((GooglePlayServicesAvailabilityException)e).getConnectionStatusCode();
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(statusCode, BaseActivity.this, REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR);
dialog.show();
} else if (e instanceof UserRecoverableAuthException) {
// Unable to authenticate, such as when the user has not yet granted
// the app access to the account, but the user can fix this.
// Forward the user to an activity in Google Play services.
Intent intent = ((UserRecoverableAuthException)e).getIntent();
startActivityForResult(intent, REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR);
}
}
});
}
public boolean isDeviceOnline() {
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
} else {
return false;
}
}
public class getTokenTask extends AsyncTask{
Activity mActivity;
String mScope;
String mEmail;
getTokenTask(Activity activity, String name, String scope) {
this.mActivity = activity;
this.mScope = scope;
this.mEmail = name;
}
#Override
protected Object doInBackground(Object[] params) {
try {
String token = fetchToken();
Preferences.saveString(Constants.KEY_BLOGGER_TOKEN, token);
} catch (IOException e) {
// The fetchToken() method handles Google-specific exceptions,
// so this indicates something went wrong at a higher level.
// TIP: Check for network connectivity before starting the AsyncTask.
}
return null;
}
/**
* Gets an authentication token from Google and handles any
* GoogleAuthException that may occur.
*/
protected String fetchToken() throws IOException {
try {
return GoogleAuthUtil.getToken(mActivity, mEmail, mScope);
} catch (UserRecoverableAuthException userRecoverableException) {
// GooglePlayServices.apk is either old, disabled, or not present
// so we need to show the user some UI in the activity to recover.
((BaseActivity)mActivity).handleException(userRecoverableException);
} catch (GoogleAuthException fatalException) {
// Some other type of unrecoverable exception has occurred.
// Report and log the error as appropriate for your app.
}
return null;
}
}
}
I've been banging my head against the wall on this one. Anyone have any ideas?
Finally figured it out.
My build.gradle file somehow ended up having a different Application ID than my manifest. I changed it so they both match the manifest, and boom! it worked.

uploading pictures to facebook using the facebook sdk for android

I am trying to upload a picture to facebook using the sdk for android. When i run the code my app crashes. Can someone help me. I am not too sure how to use the sdk. Is there another way to upload pictures?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
bm = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
// start Facebook Login
Session.openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// make request to the /me API
Request.newUploadPhotoRequest(session, bm, new Request.Callback() {
#Override
public void onCompleted(Response response)
{
// TODO Auto-generated method stub
if (isFinishing()) {
return;
}
if (response.getError() != null) { // [IF Failed Posting]
Log.d("", "photo upload problem. Error="+response.getError() );
} // [ENDIF Failed Posting]
Object graphResponse = response.getGraphObject().getProperty("id");
if (graphResponse == null || !(graphResponse instanceof String) ||
TextUtils.isEmpty((String) graphResponse)) { // [IF Failed upload/no results]
Log.d("", "failed photo upload/no response");
} else { // [ELSEIF successful upload]
fbPhotoAddress = "https://www.facebook.com/photo.php?fbid=" +graphResponse;
}
}
} ).executeAsync();
}
}
});
}
}

onConnectionFailed: ConnectionResult.getErrorCode() = 4

Here i am doing google + integartion.i am using the following code but i am facing the error which is : onConnectionFailed: ConnectionResult.getErrorCode() = 4.So please anybody help me and tell me what i am doing wrong in this code and provide me the solution for this.i will be very thankful to you.I searched a lot but found nothing.I am using the quick sample of Google plus.There is also another problem i am not able to personal information like birthday etc in this code.
public class GooglePlus extends FragmentActivity implements
ConnectionCallbacks, OnConnectionFailedListener, View.OnClickListener {
String fb_userId, fb_username;
SharedPreferences pref;
SharedPreferences.Editor editor;
private static final int STATE_DEFAULT = 0;
private static final int STATE_SIGN_IN = 1;
private static final int STATE_IN_PROGRESS = 2;
private static final int RC_SIGN_IN = 0;
private static final int DIALOG_PLAY_SERVICES_ERROR = 0;
private static final String SAVED_PROGRESS = "sign_in_progress";
// GoogleApiClient wraps our service connection to Google Play services and
// provides access to the users sign in state and Google's APIs.
private GoogleApiClient mGoogleApiClient;
// We use mSignInProgress to track whether user has clicked sign in.
// mSignInProgress can be one of three values:
//
// STATE_DEFAULT: The default state of the application before the user
// has clicked 'sign in', or after they have clicked
// 'sign out'. In this state we will not attempt to
// resolve sign in errors and so will display our
// Activity in a signed out state.
// STATE_SIGN_IN: This state indicates that the user has clicked 'sign
// in', so resolve successive errors preventing sign in
// until the user has successfully authorized an account
// for our app.
// STATE_IN_PROGRESS: This state indicates that we have started an intent to
// resolve an error, and so we should not start further
// intents until the current intent completes.
private int mSignInProgress;
// Used to store the PendingIntent most recently returned by Google Play
// services until the user clicks 'sign in'.
private PendingIntent mSignInIntent;
// Used to store the error code most recently returned by Google Play
// services
// until the user clicks 'sign in'.
private int mSignInError;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_google_plus);
pref = PreferenceManager.getDefaultSharedPreferences(this);
if (savedInstanceState != null) {
mSignInProgress = savedInstanceState.getInt(SAVED_PROGRESS,
STATE_DEFAULT);
}
mGoogleApiClient = buildGoogleApiClient();
Handler handle = new Handler();
handle.postDelayed(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
// resolveSignInError();
}
});
}
}, 1500);
}
private GoogleApiClient buildGoogleApiClient() {
// When we build the GoogleApiClient we specify where connected and
// connection failed callbacks should be returned, which Google APIs our
// app uses and which OAuth 2.0 scopes our app requests.
return new GoogleApiClient.Builder(this).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API, null)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(SAVED_PROGRESS, mSignInProgress);
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Refer to the javadoc for ConnectionResult to see what error codes
// might
// be returned in onConnectionFailed.
Log.i("", "onConnectionFailed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
if (mSignInProgress != STATE_IN_PROGRESS) {
// We do not have an intent in progress so we should store the
// latest
// error resolution intent for use when the sign in button is
// clicked.
mSignInIntent = result.getResolution();
mSignInError = result.getErrorCode();
if (mSignInProgress == STATE_SIGN_IN) {
// STATE_SIGN_IN indicates the user already clicked the sign in
// button
// so we should continue processing errors until the user is
// signed in
// or they click cancel.
resolveSignInError();
}
}
// In this sample we consider the user signed out whenever they do not
// have
// a connection to Google Play services.
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
/*
* Starts an appropriate intent or dialog for user interaction to resolve
* the current error preventing the user from being signed in. This could be
* a dialog allowing the user to select an account, an activity allowing the
* user to consent to the permissions being requested by your app, a setting
* to enable device networking, etc.
*/
private void resolveSignInError() {
if (mSignInIntent != null) {
// We have an intent which will allow our user to sign in or
// resolve an error. For example if the user needs to
// select an account to sign in with, or if they need to consent
// to the permissions your app is requesting.
try {
// Send the pending intent that we stored on the most recent
// OnConnectionFailed callback. This will allow the user to
// resolve the error currently preventing our connection to
// Google Play services.
mSignInProgress = STATE_IN_PROGRESS;
startIntentSenderForResult(mSignInIntent.getIntentSender(),
RC_SIGN_IN, null, 0, 0, 0);
} catch (SendIntentException e) {
Log.i("",
"Sign in intent could not be sent: "
+ e.getLocalizedMessage());
// The intent was canceled before it was sent. Attempt to
// connect to
// get an updated ConnectionResult.
mSignInProgress = STATE_SIGN_IN;
mGoogleApiClient.connect();
}
} else {
// Google Play services wasn't able to provide an intent for some
// error types, so we show the default Google Play services error
// dialog which may still start an intent on our behalf if the
// user can resolve the issue.
showDialog(DIALOG_PLAY_SERVICES_ERROR);
}
}
#SuppressWarnings("unused")
#Override
public void onConnected(Bundle arg0) {
// Reaching onConnected means we consider the user signed in.
Log.i("onConnected", "onConnected");
// Retrieve some profile information to personalize our app for the
// user.
Person currentUser = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
String personName = currentUser.getDisplayName();
String personPhotoUrl = currentUser.getImage().getUrl();
String personGooglePlusProfile = currentUser.getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
Log.i("personName", personName);
Log.i("email", email);
Log.i("Gender", "" + currentUser.getGender());
Log.i("Birthday", "" + currentUser.getBirthday());
// Indicate that the sign in process is complete.
mSignInProgress = STATE_DEFAULT;
/*
* fb_userId = currentUser.getId(); fb_username =
* currentUser.getDisplayName(); editor = pref.edit();
* editor.putString("fb_userId", fb_userId);
* editor.putString("fb_username", fb_username);
* editor.putString("social_provider", "google +");
*
* editor.putString("gender", currentUser.getGender());
* editor.putString("birthday", currentUser.getBirthday());
*
* editor.putString("device_name", "android");
*
* editor.putString("email",
* Plus.AccountApi.getAccountName(mGoogleApiClient)); editor.commit();
*/
}
#Override
public void onConnectionSuspended(int arg0) {
// The connection to Google Play services was lost for some reason.
// We call connect() to attempt to re-establish the connection or get a
// ConnectionResult that we can attempt to resolve.
mGoogleApiClient.connect();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case RC_SIGN_IN:
if (resultCode == RESULT_OK) {
// If the error resolution was successful we should continue
// processing errors.
mSignInProgress = STATE_SIGN_IN;
} else {
// If the error resolution was not successful or the user
// canceled,
// we should stop processing errors.
mSignInProgress = STATE_DEFAULT;
}
if (!mGoogleApiClient.isConnecting()) {
// If Google Play services resolved the issue with a dialog then
// onStart is not called so we need to re-attempt connection
// here.
mGoogleApiClient.connect();
}
break;
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_PLAY_SERVICES_ERROR:
if (GooglePlayServicesUtil.isUserRecoverableError(mSignInError)) {
return GooglePlayServicesUtil.getErrorDialog(mSignInError,
this, RC_SIGN_IN,
new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
Log.e("",
"Google Play services resolution cancelled");
mSignInProgress = STATE_DEFAULT;
}
});
} else {
return new AlertDialog.Builder(this)
.setMessage(R.string.play_services_error)
.setPositiveButton(R.string.close,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
Log.e("",
"Google Play services error could not be "
+ "resolved: "
+ mSignInError);
mSignInProgress = STATE_DEFAULT;
// mStatus.setText(R.string.status_signed_out);
}
}).create();
}
default:
return super.onCreateDialog(id);
}
}
}
I had the same problem. I solved in google api console >> consent screen, and adding a Product Name.
I try this tutorial: http://www.androidhive.info/2014/02/android-login-with-google-plus-account-1/
In the main activity you need change .addApi(Plus.API, null) by .addApi(Plus.API, Plus.PlusOptions.builder().build())
For me the problem was that I had not created the credentials for the app.
Went to Google Developers Console > Credentials > Create New Client ID
filled the corresponding package name and SHA1 for my app, reran the app and then it worked!
In case you are using MapView, make sure you are following the guidelines
i.e.
"When using the API in fully interactive mode, users of this class must forward all the activity life cycle methods to the corresponding methods in the MapView class. Examples of the life cycle methods include onCreate(), onDestroy(), onResume(), and onPause(). When using the API in lite mode, forwarding lifecycle events is optional. For details, see the lite mode documentation."
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}

How to share the status for FB in Android programatically

I want to share the text/image programatically from my app on facebook.How should I proceed for that.After lots of googling I found lots of sample apps but as the latest FB SDK is deprecated those APIs it is hard to find the way using new SDK.Please help me out for this issue.
private void publishFeedDialog() {
Bundle params = new Bundle();
params.putString("name", "Facebook SDK for Android");
params.putString("caption", "Build great social apps and get more installs.");
params.putString("description", "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
params.putString("link", "https://developers.facebook.com/android");
params.putString("picture", "https://raw.github.com/fbsamples/ios-3.x- howtos/master/Images/iossdk_logo.png");
WebDialog feedDialog = (
new WebDialog.FeedDialogBuilder(getApplicationContext(),
Session.getActiveSession(),
params))
.setOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(Bundle values,
FacebookException error) {
if (error == null) {
// When the story is posted, echo the success
// and the post Id.
final String postId = values.getString("post_id");
if (postId != null) {
Toast.makeText(getApplicationContext(),
"Posted story, id: "+postId,
Toast.LENGTH_SHORT).show();
} else {
// User clicked the Cancel button
Toast.makeText(getApplicationContext(),
"Publish cancelled",
Toast.LENGTH_SHORT).show();
}
} else if (error instanceof FacebookOperationCanceledException) {
// User clicked the "x" button
Toast.makeText(getApplicationContext(),
"Publish cancelled",
Toast.LENGTH_SHORT).show();
} else {
// Generic, ex: network error
Toast.makeText(getApplicationContext(),
"Error posting story",
Toast.LENGTH_SHORT).show();
}
}
})
.build();
feedDialog.show();
}
This is what i get for fb API 3.5 doc & which I have tried but it is crashing the app by saying session is null.
Here your session is null because you have not started it yet.
You have to start your session after login.
You can achieve this by using
Session.openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
});
For more information try going through the tutorials from http://developers.facebook.com/docs/android/scrumptious/authenticate/. These are really helpful.
Here is how I implemented --
This class is used to do initial stuffs to facebook
LoginFacebookClass
/**
* for integrating facebook in your app..
* Firstly import FacebookSDK lib project and add in your project as lib project.
* then
* create an instance of this class
* and, then call the facebook login method by passing reference of your activity and true, if you want to fetch data and, false if you want to share data on faceboko
* Please do whatever you want in the interface callback methods
* implemented by this class
*
*
* Note: Please write a line exactly in your activity's on activity result as
* -- Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
* here, 'Session' is Class of Facebook.
* 'this' is reference of your activity
*/
public class FacebookLoginClass implements FB_Callback
{
Context context;
FBImPlmentation fbImpl;
String mImageURLString = "", mPhotoTypeString = "";
// private FBBean userDataBean;
/**
* constructor for FacebookLoginClass
* #param con : context of activity
* #param string
* #param mImageURLString2
*/
public FacebookLoginClass(Context con)
{
this.context = con;
fbImpl = FBImPlmentation.getInstance(context, this);
}
public FacebookLoginClass(Context con, String imageURLString, String photoType)
{
this.context = con;
fbImpl = FBImPlmentation.getInstance(context, this);
mImageURLString = imageURLString;
mPhotoTypeString = photoType;
}
/**
* method for initiating facebook Login
* #param isDataFetch : true for fetching user data, false for sharing on wall
*/
public void facebookLogin(boolean isDataFetch)
{
fbImpl.CheckSession(isDataFetch);
}
/**
* method for facebookLogout
*/
public void facebookLogout()
{
fbImpl.fbLogout();
}
#Override
public void onLogin(Session s)
{
fbImpl.getDataFromFB(s);
}
#Override
public void onLoginForShareData()
{
Log.e("facebook.", "True in..........");
Bundle postParams = new Bundle();
postParams.putString("name", "");
postParams.putString("caption", "");
postParams.putString("description", " Android, share your pics and videos");
if (mPhotoTypeString.equalsIgnoreCase("photo"))
{
postParams.putString("picture", mImageURLString);
}
else
{
postParams.putString("link", "");
}
fbImpl.publishFeedDialog(postParams);
}
#Override
public void onAuthFailiure()
{
}
#Override
public void onUserData(FBBean fbUserDataBean)
{
try
{
if (BejoelUtility.isNetworkAvailable(context))
{
String imageURLString = "http://graph.facebook.com/" + fbUserDataBean.getUserID() + "/picture?type=large";
new FacebookTwitterLoginAsyncTask(context, fbUserDataBean.getFirstNAme(), fbUserDataBean.getLastName(),
fbUserDataBean.getMailId(), fbUserDataBean.getUserBday(), fbUserDataBean.getUserSex(), "", "", imageURLString,
fbUserDataBean.getAccessToken(), "facebook").execute();
}
else
{
BejoelUtility.showMsgDialog(context, context.getString(R.string.app_name), context.getString(R.string.no_internet));
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
#Override
public void onPost(boolean postStatus)
{
// TODO Auto-generated method stub
}
#Override
public void onFriendRequest(boolean shareAppStatus)
{
// TODO Auto-generated method stub
}
#Override
public void onLogout(boolean status)
{
// TODO Auto-generated method stub
}
}
This class interact with facebook
public class FBImPlmentation
{
public static List<String> READ_PERMISSIONS = Arrays.asList("email");
public List<String> WRITE_PERMISSIONS = Arrays.asList("publish_actions");
private static FBImPlmentation fbImpl;
private FB_Callback mInterface;
private static Activity activity;
boolean isDataFetch=false;
private String mAccessTokenString = "";
/**
* constructor for facebookImplementation
* #param con :context of activity via FacebookLogin Class
* #param mInterface : refrence of class implementing FB_Callback interface..as in our case,
* it is refrence of FacebookLogin Class
* #return : instance of FBImplementation
*/
public static FBImPlmentation getInstance(Context con, FB_Callback mInterface)
{
activity = (Activity) con;
if (fbImpl == null)
fbImpl = new FBImPlmentation();
fbImpl.mInterface = mInterface;
return fbImpl;
}
/**
* method to be called for facebook Logout
*/
public void fbLogout()
{
if (Session.getActiveSession() != null)
{
Session.getActiveSession().closeAndClearTokenInformation();
}
Session.setActiveSession(null);
mInterface.onLogout(true);
}
/**
* method for checking session.
* if session is not open, then open a new session.
* If session is already open then..just call the fbcallback onlogin method
* #param isDataFetch2
*/
public void CheckSession(boolean isDataFetch2)
{
fbImpl.isDataFetch= isDataFetch2;
Session s = Session.getActiveSession();
if (s != null && s.isOpened())
{
if(isDataFetch)
mInterface.onLogin(s);
else
mInterface.onLoginForShareData();
mAccessTokenString = s.getAccessToken();
}
else
{
Session.openActiveSession(activity, true, mFBCallback);
}
}
// Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(activity, permissions);
Session.StatusCallback mFBCallback = new Session.StatusCallback()
{
// call method is always called on session state change
#Override
public void call(Session session, SessionState state, Exception exception)
{
if (session.isOpened())
{
List<String> permissions = session.getPermissions();
if (!isSubsetOf(READ_PERMISSIONS, permissions))
{
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(activity, READ_PERMISSIONS);
session.requestNewReadPermissions(newPermissionsRequest);
return;
}
else if(isDataFetch)
{
mInterface.onLogin(session);
}
else
{
mInterface.onLoginForShareData();
}
}
}
};
/**
* method for fetching the user data
* #param session : it takes the refrence of active session
*/
public void getDataFromFB(Session session)
{
Request.executeMeRequestAsync(session, new Request.GraphUserCallback()
{
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response)
{
if (user != null)
{
// code to retrieve user's data and pass to signup fragment
FBBean fbUserDataBean = new FBBean();
if (mAccessTokenString != null)
fbUserDataBean.setAccessToken(mAccessTokenString);
else
{
fbUserDataBean.setAccessToken("");
}
if (user.getUsername() != null && !(user.getUsername().equals(null)))
fbUserDataBean.setUserName(user.getUsername());
else
{
fbUserDataBean.setUserName("");
}
if (user.getFirstName() != null && !(user.getFirstName().equals(null)))
fbUserDataBean.setFirstNAme(user.getFirstName());
else
{
fbUserDataBean.setFirstNAme("");
}
if (user.getLastName() != null && !(user.getLastName().equals(null)))
fbUserDataBean.setLastName(user.getLastName());
else
{
fbUserDataBean.setLastName("");
}
if (user.getBirthday() != null && !(user.getBirthday().equals(null)))
fbUserDataBean.setUserBday(user.getBirthday());
else
{
fbUserDataBean.setUserBday("");
}
if (user.asMap().get("gender") != null)
{
fbUserDataBean.setUserSex(user.asMap().get("gender").toString());
}
else
{
fbUserDataBean.setUserSex("");
}
if (user.getProperty("email") != null && !(user.getProperty("email").equals(null)))
fbUserDataBean.setMailId(user.getProperty("email").toString());
else
{
fbUserDataBean.setMailId("");
}
if (user.getId() != null && !(user.getId().equals(null)))
fbUserDataBean.setUserID(user.getId());
else
{
fbUserDataBean.setUserID("");
}
// String[] sportsArray = FacebookUtils.getSportsArray(user.getInnerJSONObject());
// if (sportsArray != null && !(sportsArray.equals(null)))
// fbUserDataBean.setSportsname(sportsArray);
mInterface.onUserData(fbUserDataBean);
}
}
});
}
private boolean isSubsetOf(Collection<String> subset, Collection<String> superset)
{
for (String string : subset)
{
if (!superset.contains(string))
{
return false;
}
}
return true;
}
/**
* method for publishing posts
*/
public void publishFeedDialog(Bundle postParams)
{
Session s = Session.getActiveSession();
List<String> permissions = s.getPermissions();
if (!isSubsetOf(WRITE_PERMISSIONS, permissions))
{
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(activity,
WRITE_PERMISSIONS);
s.requestNewPublishPermissions(newPermissionsRequest);
return;
}
// Bundle postParams = new Bundle();
// postParams.putString("name", "Facebook SDK for Android");
// postParams.putString("caption", "Build great social apps and get more installs.");
// postParams.putString("description", "Video by Lata manadjahgkfdjhaskjd akhgfkjashfkjash");
// postParams.putString("link", "");
// postParams.putString("picture", "");
WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(activity, Session.getActiveSession(), postParams))
.setOnCompleteListener(new OnCompleteListener()
{
#Override
public void onComplete(Bundle values, FacebookException error)
{
if (error == null)
{
// When the story is posted, echo the success
// and the post Id.
final String postId = values.getString("post_id");
if (postId != null)
{
mInterface.onPost(true);
}
else
{
// User clicked the Cancel button
mInterface.onPost(false);
}
}
else
if (error instanceof FacebookOperationCanceledException)
{
// User clicked the "x" button
// Toast.makeText(MainActivity.this.getApplicationContext(), "Publish cancelled",
// Toast.LENGTH_SHORT).show();
mInterface.onPost(false);
}
else
{
// Generic, ex: network error
// Toast.makeText(MainActivity.this.getApplicationContext(), "Error posting story",
// Toast.LENGTH_SHORT).show();
mInterface.onAuthFailiure();
}
}
}).build();
feedDialog.show();
}
}

Categories

Resources