Get friend list using latest facebook sdk in android - android

MainActivity.java
public class MainActivity extends ActionBarActivity {
RequestAsyncTask task = null;
private SharedPreferences preferences;
private String AccessToken = "";
private static final List<String> PERMISSIONS = Arrays
.asList("publish_actions");
private static final List<String> PERMISSIONSFRD = Arrays
.asList("user_friends");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;
private LoginButton btn_fb_login;
private UiLifecycleHelper uiHelper;
private PendingAction pendingAction = PendingAction.NONE;
private GraphUser user;
private final String PENDING_ACTION_BUNDLE_KEY = "com.facebook.samples.hellofacebook:PendingAction";
private enum PendingAction {
NONE, POST_PHOTO, POST_STATUS_UPDATE
}
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback() {
#Override
public void onError(FacebookDialog.PendingCall pendingCall,
Exception error, Bundle data) {
// Log.e("HelloFacebook", String.format("Error: %s",
// error.toString()));
}
#Override
public void onComplete(FacebookDialog.PendingCall pendingCall,
Bundle data) {
// Log.e("HelloFacebook", "Success!");
}
};
private Button btn_share_fb;
Button btn_frds;
private boolean isShareProcess = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(this, callback);
uiHelper.onCreate(savedInstanceState);
if (savedInstanceState != null) {
String name = savedInstanceState
.getString(PENDING_ACTION_BUNDLE_KEY);
pendingAction = PendingAction.valueOf(name);
}
System.out.println("Start");
Log.e("FB LOGIN--->", "----->Login");
setContentView(R.layout.activity_main);
preferences = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
btn_share_fb = (Button) findViewById(R.id.btn_share_fb);
btn_frds = (Button)findViewById(R.id.btn_frds);
btn_frds.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
getFrdList();
}
});
btn_fb_login = (LoginButton) findViewById(R.id.btn_fb_login);
btn_fb_login.setReadPermissions(Arrays.asList("basic_info", "email",
"user_birthday", "user_location"));
btn_fb_login.setUserInfoChangedCallback(new UserInfoChangedCallback() {
#Override
public void onUserInfoFetched(GraphUser user) {
// TODO Auto-generated method stub
MainActivity.this.user = user;
try {
Session session = Session.getActiveSession();
boolean enableButtons = (session != null && session
.isOpened());
if (enableButtons && user != null) {
Log.e("-->", "" + session.getPermissions());
Log.e("fb user.getId", "" + user.getId());
Log.e("fb user.getFirstName",
"" + user.getFirstName());
Log.e("fb user.getMiddleName",
"" + user.getMiddleName());
Log.e("fb user.getLastName",
"" + user.getLastName());
Log.e("fb user.getUsername",
"" + user.getUsername());
Log.e("fb user.getBirthday",
"" + user.getBirthday());
Log.e("fb user.getLocation",
"" + user.getLocation());
Log.e("fb user.gender",
""
+ user.asMap().get("gender")
.toString());
Log.e("fb user email", "Email "
+ user.asMap().get("email"));
AccessToken = session.getAccessToken();
Editor PEDIT = preferences.edit();
PEDIT.putBoolean(
GeneralClass.temp_isFbLoginShare, true);
PEDIT.commit();
setFbLoginDetails1();
} else {
// profilePictureView.setProfileId(null);
// greeting.setText(null);
// btn_fb_login.setVisibility(View.VISIBLE);
Log.e("FB--->", "----> NOT LOGIN");
Editor PEDIT = preferences.edit();
PEDIT.putBoolean(
GeneralClass.temp_isFbLoginShare, false);
PEDIT.commit();
}
} catch (Exception e) {
e.printStackTrace();
// Log.e("error get facebook details-->",
// "error get facebook details");
}
handlePendingAction();
}
});
btn_share_fb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(!FbSharing.checkUserFBLogin()){
if (preferences.getBoolean(
GeneralClass.temp_isFbLoginShare, false) == true) {
// publishFeedDialog();
/**
* original method
* */
Session session = Session.getActiveSession();
boolean enableButtons = (session != null && session
.isOpened());
if (enableButtons) {
publishStory();
isShareProcess = true;
} else {
// Log.e("error:",
// "please login again in facebook");
}
// share();
// getListofFacebookFriend();
} else {
GeneralClass.showToast("Please login with Facebook",
getApplicationContext());
btn_fb_login.setVisibility(View.VISIBLE);
}
}else if(FbSharing.checkUserFBLogin()){
try {
publishStory();
} catch (Exception e) {
// Log.e("error share facebook user",
// "error share facebook user");
e.printStackTrace();
}
}
}
});
setFbLoginDetails();
}
protected void setFbLoginDetails() {
if (FbSharing.checkUserFBLogin()) {
btn_fb_login.setVisibility(View.GONE);
btn_share_fb.setVisibility(View.VISIBLE);
} else if (preferences.getBoolean(GeneralClass.temp_isFbLoginShare,
false) == true) {
btn_fb_login.setVisibility(View.GONE);
btn_share_fb.setVisibility(View.VISIBLE);
} else {
btn_fb_login.setVisibility(View.GONE);
btn_share_fb.setVisibility(View.VISIBLE);
}
}
protected void setFbLoginDetails1() {
if (FbSharing.checkUserFBLogin()) {
btn_fb_login.setVisibility(View.GONE);
btn_share_fb.setVisibility(View.VISIBLE);
} else if (preferences.getBoolean(GeneralClass.temp_isFbLoginShare,
false) == true) {
btn_fb_login.setVisibility(View.VISIBLE);
btn_share_fb.setVisibility(View.VISIBLE);
} else {
btn_fb_login.setVisibility(View.GONE);
btn_share_fb.setVisibility(View.VISIBLE);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data, dialogCallback);
}
#Override
protected void onResume() {
super.onResume();
uiHelper.onResume();
// Call the 'activateApp' method to log an app event for use in
// analytics and advertising reporting. Do so in
// the onResume methods of the primary Activities that an app may be
// launched into.
AppEventsLogger.activateApp(this);
updateUI("onResume");
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
if (pendingAction != PendingAction.NONE
&& (exception instanceof FacebookOperationCanceledException || exception instanceof FacebookAuthorizationException)) {
new AlertDialog.Builder(MainActivity.this)
.setTitle(R.string.cancelled)
.setMessage(R.string.permission_not_granted)
.setPositiveButton(R.string.ok, null).show();
pendingAction = PendingAction.NONE;
} else if (state == SessionState.OPENED_TOKEN_UPDATED) {
handlePendingAction();
}
updateUI("onSessionStateChange");
}
#SuppressWarnings("incomplete-switch")
private void handlePendingAction() {
PendingAction previouslyPendingAction = pendingAction;
// These actions may re-set pendingAction if they are still pending, but
// we assume they
// will succeed.
pendingAction = PendingAction.NONE;
switch (previouslyPendingAction) {
case POST_PHOTO:
// postPhoto();
break;
case POST_STATUS_UPDATE:
// postStatusUpdate();
break;
}
}
private void updateUI(String fromWhere) {
// Log.e("fromWhere", "" + fromWhere);
Session session = Session.getActiveSession();
boolean enableButtons = (session != null && session.isOpened());
if (enableButtons && user != null) {
AccessToken = session.getAccessToken();
Editor PEDIT = preferences.edit();
PEDIT.putBoolean(GeneralClass.temp_isFbLoginShare, true);
PEDIT.commit();
setFbLoginDetails();
} else {
Editor PEDIT = preferences.edit();
PEDIT.putBoolean(GeneralClass.temp_isFbLoginShare, false);
PEDIT.commit();
}
}
public void share() {
try {
Session session = Session.getActiveSession();
boolean enableButtons = (session != null && session.isOpened());
if (enableButtons) {
Bundle bundle = new Bundle();
bundle.putString("caption", "Harlem Shake Launcher for Android");
bundle.putString("description",
"Your android can do the Harlem Shake. Download it from google play");
bundle.putString("link",
"https://play.google.com/store/apps/details?id=mobi.shush.harlemlauncher");
bundle.putString("name", "Harlem Shake Launcher");
bundle.putString("picture", "http://shush.mobi/bla.png");
new WebDialog.FeedDialogBuilder(getApplicationContext(),
Session.getActiveSession(), bundle).build().show();
}
} catch (Exception e) {
// Log.e("error share on facebook", "error share on facebook");
e.printStackTrace();
}
}
#SuppressWarnings("unused")
private void publishFeedDialog() {
try {
Session session = Session.getActiveSession();
boolean enableButtons = (session != null && session.isOpened());
if (enableButtons) {
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()
.getApplicationContext(),
"Publish cancelled",
Toast.LENGTH_SHORT).show();
}
} else if (error instanceof FacebookOperationCanceledException) {
// User clicked the "x" button
Toast.makeText(
getApplicationContext()
.getApplicationContext(),
"Publish cancelled",
Toast.LENGTH_SHORT).show();
} else {
// Generic, ex: network error
Toast.makeText(
getApplicationContext()
.getApplicationContext(),
"Error posting story",
Toast.LENGTH_SHORT).show();
}
}
}).build();
feedDialog.show();
}
} catch (Exception e) {
// Log.e("error share on facebook", "error share on facebook");
e.printStackTrace();
}
}
private boolean isSubsetOf(Collection<String> subset,
Collection<String> superset) {
for (String string : subset) {
if (!superset.contains(string)) {
return false;
}
}
return true;
}
private void publishStory() {
Session session = Session.getActiveSession();
if (session != null) {
GeneralClass.showToast("Wait while we share in facebook",
getApplicationContext());
// Check for publish permissions
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(
this, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
return;
}
Bundle postParams = new Bundle();
postParams.putString("name", "Lolipop for Android");
postParams.putString("caption",
"Get better experience!");
postParams.putString("description",
"Get better experience!");
postParams.putString("link",
"https://developers.facebook.com/android");
postParams
.putString("picture",
"https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
Request.Callback callback = new Request.Callback() {
public void onCompleted(Response response) {
JSONObject graphResponse = response.getGraphObject()
.getInnerJSONObject();
String postId = null;
try {
postId = graphResponse.getString("id");
} catch (JSONException e) {
Log.i("-->", "JSON error " + e.getMessage());
}
FacebookRequestError error = response.getError();
if (error != null) {
Toast.makeText(getApplicationContext(),
error.getErrorMessage(), Toast.LENGTH_SHORT)
.show();
isShareProcess = false;
} else {
Toast.makeText(
getApplicationContext(),
"Successfully Shared on Facebook, postid - "
+ postId, Toast.LENGTH_LONG).show();
isShareProcess = false;
new GetLists().execute();
}
task = null;
}
};
Request request = new Request(session, "me/feed", postParams,
HttpMethod.POST, callback);
task = new RequestAsyncTask(request);
task.execute();
}
}
private void getFrdList() {
Session session = Session.getActiveSession();
if (session != null) {
GeneralClass.showToast("Wait while we get List",
getApplicationContext());
// Check for publish permissions
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONSFRD, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(
this, PERMISSIONSFRD);
session.requestNewPublishPermissions(newPermissionsRequest);
return;
}
new Request(
session,
"/me/friends",
null,
HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
/* handle the result */
JSONObject graphResponse = response.getGraphObject()
.getInnerJSONObject();
Log.e("JSON RESPONSE---->", "FRIEND LIST--->"+ graphResponse.toString());
}
}).executeAsync();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
if (isShareProcess == false) {
if (task != null) {
// Log.e("back press", "wait for share");
} else {
task = null;
// Log.e("back press", "no wait for share");
super.onBackPressed();
}
}
}
}
above code is displaying following output when click on friends button:
FRIEND LIST--->{"summary":{"total_count":10},"data":[]}
i dont know how to get list of friends. i already did R&D for this. but nothing getting actual result. i know in latest sdk, its not possible to get all friends but only those who used your app. i also try to run my app with two different users who are both friends. but still not getting in result.
kindly help me in this problem.

Since v2.0, it is not possible to get a list of ALL friends anymore. You will only get those friends who authorized your App too. That is why "data" is empty.
See the changelog for more information: https://developers.facebook.com/docs/apps/changelog
Check out the large amount of other threads about that exact same issue too, especially this one offers additional information: Facebook Graph Api v2.0+ - /me/friends returns empty, or only friends who also use my app

Related

How to share app link on facebook without have the app installed?

I am using the sdk from facebook to share my app link. When I have the facebook app installed on my device, it works fine.
But I want that the user can share it without have the app installed on device.
The link to the tutorial from facebook to do that is broken and I get this example of Feed Dialog on the internet:
private void publishFeedDialog() {
Session session = Session.getActiveSession();
Bundle params = new Bundle();
params.putString("name", "***");
params.putString("caption", "***");//caption
params.putString("picture", ***");
params.putString("link", "***");
Request.Callback callback = new Request.Callback() {
public void onCompleted(Response response) {
FacebookRequestError error = response.getError();
if (error != null) {
Log.i("Tag", "FacebookRequestError" + error.getErrorMessage());
Toast.makeText(CompartilhamentoActivity.this, error.getErrorMessage(), Toast.LENGTH_SHORT).show();
} else {
Log.i("Tag", "FacebookRequest Done");
Toast.makeText(CompartilhamentoActivity.this, "Story Published to Your Wall", Toast.LENGTH_LONG).show();
}
}
};
Request request = new Request(session, "me/feed", params, HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
When I use this method I get this error "FacebookRequestErrorcom.facebook.FacebookException: Session provided to a Request in un-opened state."
Check this one
public class FacebookActivity extends Activity {
String p_name;
String p_desc;
String path;
String timeStamp;
String senduri;
Boolean canshare=false;
private static final String PERMISSION = "publish_actions";
int fun=0;
SharedPreferences settings;
WebDialog feedDialog;
Button facebookButton;
private static final String TAG = "Facebook";
boolean isClicked=false;
private Session.StatusCallback statusCallback =
new Session.StatusCallback() {
#Override
public void call(Session session,
SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_facebook);
//facebook connector initialization************************
Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
Session session = Session.getActiveSession();
if (session == null) {
if (savedInstanceState != null) {
session = Session.restoreSession(this, null, statusCallback, savedInstanceState);
}
if (session == null) {
session = new Session(this);
}
Session.setActiveSession(session);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
}
}
try {
PackageInfo info = getPackageManager().getPackageInfo(
getApplicationContext().getPackageName(), PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures)
{
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (NameNotFoundException ex) {
} catch (NoSuchAlgorithmException ex2) {
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.facebook, menu);
return true;
}
#Override
protected void onStart() {
Log.d(TAG, "onStart");
super.onStart();
Session.getActiveSession().addCallback(statusCallback);
}
#Override
protected void onDestroy() {
Log.d(TAG, "onDestroy");
super.onDestroy();
}
#Override
public void onStop() {
Log.d(TAG, "onStop");
super.onStop();
Session.getActiveSession().removeCallback(statusCallback);
}
public void onClickPublishPic(View v) {
//postPhoto();
fun=1;
onClickLogin();
isClicked=true;
}
public void onClickPublishStory(View v) {
//postPhoto();
fun=2;
onClickLogin();
isClicked=true;
}
protected void onSessionStateChange(Session session, SessionState state,
Exception exception) {
session = Session.getActiveSession();
if (session.isOpened()) {
if(fun==1){
postPhoto();
}else if(fun==2){
publishStory();
}
} else {
//nothing .. maybe message
}
}
private void onClickLogin() {
Session.openActiveSession(this, true, statusCallback);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
//Session.openActiveSession(this, true, statusCallback);
Log.d("msg"," "+resultCode);
}
private void postPhoto() {
Session session = Session.getActiveSession();
if (session != null) {
//pendingAction = action;
if (hasPublishPermission()) {
Bitmap image = BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_launcher);
Request request = Request.newUploadPhotoRequest(session, image, new Request.Callback() {
#Override
public void onCompleted(Response response) {
//showPublishResult(getString(R.string.app_name), response.getGraphObject(), response.getError());
Toast.makeText(getBaseContext(),
"Image Uploaded to facebook",
Toast.LENGTH_SHORT).show();
}
});
Bundle params = request.getParameters();
params.putString("name", "My Science Lab Diagram");
request.setParameters(params);
Request.executeBatchAsync(request);
// We can do the action right away.
//handlePendingAction();
//return;
} else if (session.isOpened()) {
// We need to get new permissions, then complete the action when we get called back.
session.requestNewPublishPermissions(new Session.NewPermissionsRequest(this, PERMISSION));
//return;
}
}
}
private void publishStory() {
Session session = Session.getActiveSession();
if (session != null){
// Check for publish permissions
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new Session
.NewPermissionsRequest(this, PERMISSIONS);
session.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", "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
postParams.putString("link", "https://developers.facebook.com/android");
postParams.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
Request.Callback callback= new Request.Callback() {
public void onCompleted(Response response) {
JSONObject graphResponse = response
.getGraphObject()
.getInnerJSONObject();
String postId = null;
try {
postId = graphResponse.getString("id");
} catch (JSONException e) {
Log.i(TAG,
"JSON error "+ e.getMessage());
}
FacebookRequestError error = response.getError();
if (error != null) {
Toast.makeText(FacebookActivity.this
.getApplicationContext(),
error.getErrorMessage(),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(FacebookActivity.this
.getApplicationContext(),
postId,
Toast.LENGTH_LONG).show();
}
}
};
Request request = new Request(session, "me/feed", postParams,
HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
}
private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
for (String string : subset) {
if (!superset.contains(string)) {
return false;
}
}
return true;
}
private boolean hasPublishPermission() {
Session session = Session.getActiveSession();
return session != null && session.getPermissions().contains("publish_actions");
}
}

Can't pass custom text to Facebook Wall Post - Android API

I'm trying to allow the users of my app to publish stories on their walls from my application for things such as Achievements(for example) within my application. Here is the activity code, adapted from the HelloFacebookActivitySample:
With both activities, I can see my app name, description, and link no problem when I post. Using the latest version of the FB SDK. However, the string (message) that I pass through the newStatusUpdateRequest() method is not displayed.
(In this attempt, I'm trying to pass text from a text view)
The first way I tried it:
public class Settings_Facebook extends FragmentActivity {
//Constants
private static final String PERMISSION = "publish_actions";
private final String PENDING_ACTION_BUNDLE_KEY = "com.facebook.MyApp:PendingAction";
//Views
private Button postStatusUpdateButton;
private Button postPhotoButton;
private LoginButton loginButton;
private ProfilePictureView profilePictureView;
private TextView greeting;
//Variables
private PendingAction pendingAction = PendingAction.NONE;
private ViewGroup controlsContainer;
private GraphUser user;
private GraphPlace place;
private List<GraphUser> tags;
private boolean canPresentShareDialog;
private enum PendingAction {
NONE,
POST_PHOTO,
POST_STATUS_UPDATE
}
private UiLifecycleHelper uiHelper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(this, callback);
uiHelper.onCreate(savedInstanceState);
if (savedInstanceState != null) {
String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
pendingAction = PendingAction.valueOf(name);
}
setContentView(R.layout.activity_settings__facebook);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {
#Override
public void onUserInfoFetched(GraphUser user) {
Settings_Facebook.this.user = user;
updateUI();
// It's possible that we were waiting for this.user to be populated in order to post a
// status update.
handlePendingAction();
}
});
profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture);
greeting = (TextView) findViewById(R.id.greeting);
postStatusUpdateButton = (Button) findViewById(R.id.postStatusUpdateButton);
postStatusUpdateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickPostStatusUpdate();
}
});
postPhotoButton = (Button) findViewById(R.id.postPhotoButton);
postPhotoButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickPostPhoto();
}
});
controlsContainer = (ViewGroup) findViewById(R.id.main_ui_container);
canPresentShareDialog = FacebookDialog.canPresentShareDialog(this,
FacebookDialog.ShareDialogFeature.SHARE_DIALOG);
}
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback() {
#Override
public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data) {
Log.d("HelloFacebook", String.format("Error: %s", error.toString()));
}
#Override
public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) {
Log.d("HelloFacebook", "Success!");
}
};
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data, dialogCallback);
}
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (pendingAction != PendingAction.NONE &&
(exception instanceof FacebookOperationCanceledException ||
exception instanceof FacebookAuthorizationException)) {
new AlertDialog.Builder(Settings_Facebook.this)
.setTitle(R.string.cancelled)
.setMessage(R.string.permission_not_granted)
.setPositiveButton(R.string.ok, null)
.show();
pendingAction = PendingAction.NONE;
} else if (state == SessionState.OPENED_TOKEN_UPDATED) {
handlePendingAction();
}
updateUI();
}
private void updateUI() {
Session session = Session.getActiveSession();
boolean enableButtons = (session != null && session.isOpened());
postStatusUpdateButton.setEnabled(enableButtons || canPresentShareDialog);
postPhotoButton.setEnabled(enableButtons);
if (enableButtons && user != null) {
profilePictureView.setProfileId(user.getId());
greeting.setText(getString(R.string.hello_user, user.getFirstName()));
} else {
profilePictureView.setProfileId(null);
greeting.setText(null);
}
}
#SuppressWarnings("incomplete-switch")
private void handlePendingAction() {
PendingAction previouslyPendingAction = pendingAction;
// These actions may re-set pendingAction if they are still pending, but we assume they
// will succeed.
pendingAction = PendingAction.NONE;
switch (previouslyPendingAction) {
case POST_PHOTO:
postPhoto();
break;
case POST_STATUS_UPDATE:
postStatusUpdate();
break;
}
}
private interface GraphObjectWithId extends GraphObject {
String getId();
}
private void showPublishResult(String message, GraphObject result, FacebookRequestError error) {
String title = null;
String alertMessage = null;
if (error == null) {
title = getString(R.string.success);
String id = result.cast(GraphObjectWithId.class).getId();
alertMessage = getString(R.string.successfully_posted_post, message, id);
} else {
title = getString(R.string.error);
alertMessage = error.getErrorMessage();
}
new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(alertMessage)
.setPositiveButton(R.string.ok, null)
.show();
}
private void onClickPostStatusUpdate() {
performPublish(PendingAction.POST_STATUS_UPDATE, canPresentShareDialog);
}
private FacebookDialog.ShareDialogBuilder createShareDialogBuilder() {
return new FacebookDialog.ShareDialogBuilder(this)
.setName("MyApplication")
.setDescription("The description of the app")
.setLink("https://play.google.com/store/");
}
private void postStatusUpdate() {
final EditText simpleEditText = (EditText) findViewById(R.id.editStatus);
final String message = simpleEditText.getText().toString();
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", "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
postParams.putString("link", "https://developers.facebook.com/android");
postParams.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
if (canPresentShareDialog) {
FacebookDialog shareDialog = createShareDialogBuilder().build();
uiHelper.trackPendingDialogCall(shareDialog.present());
}
else if (user != null && hasPublishPermission()) {
Session session = Session.getActiveSession();
Request request = new Request(session,"me/feed",postParams,HttpMethod.POST);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
// .newStatusUpdateRequest(Session.getActiveSession(), message, place, tags, new Request.Callback() {
// #Override
// public void onCompleted(Response response) {
// showPublishResult(message, response.getGraphObject(), response.getError());
// }
// });
// request.executeAsync();
}
else {
pendingAction = PendingAction.POST_STATUS_UPDATE;
}
}
private void onClickPostPhoto() {
performPublish(PendingAction.POST_PHOTO, false);
}
private void postPhoto() {
if (hasPublishPermission()) {
Bitmap image = BitmapFactory.decodeResource(this.getResources(), R.drawable.button_focus);
Request request = Request.newUploadPhotoRequest(Session.getActiveSession(), image, new Request.Callback() {
#Override
public void onCompleted(Response response) {
showPublishResult(getString(R.string.photo_post), response.getGraphObject(), response.getError());
}
});
request.executeAsync();
} else {
pendingAction = PendingAction.POST_PHOTO;
}
}
private boolean hasPublishPermission() {
Session session = Session.getActiveSession();
return session != null && session.getPermissions().contains("publish_actions");
}
private void performPublish(PendingAction action, boolean allowNoSession) {
Session session = Session.getActiveSession();
if (session != null) {
pendingAction = action;
if (hasPublishPermission()) {
// We can do the action right away.
handlePendingAction();
return;
} else if (session.isOpened()) {
// We need to get new permissions, then complete the action when we get called back.
session.requestNewPublishPermissions(new Session.NewPermissionsRequest(this, PERMISSION));
return;
}
}
if (allowNoSession) {
pendingAction = action;
handlePendingAction();
}
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
protected void onResume() {
super.onResume();
uiHelper.onResume();
updateUI();
}
}
(in this attempt I'm passing a bundle of parameters)
The second way I tried it(Just the postStatusUpdate() method was changed):
private void postStatusUpdate() {
final EditText simpleEditText = (EditText) findViewById(R.id.editStatus);
final String message = simpleEditText.getText().toString();
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", "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
postParams.putString("link", "https://developers.facebook.com/android");
postParams.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
if (canPresentShareDialog) {
FacebookDialog shareDialog = createShareDialogBuilder().build();
uiHelper.trackPendingDialogCall(shareDialog.present());
}
else if (user != null && hasPublishPermission()) {
Session session = Session.getActiveSession();
Request request = new Request(session,"me/feed",postParams,HttpMethod.POST);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
else {
pendingAction = PendingAction.POST_STATUS_UPDATE;
}
}
For achievements, you can either use the Achievements API or Open Graph Actions/Objects. Since the Achievements are only available for games, Open Graph Actions are the way to go. Here are some links to get you started:
https://developers.facebook.com/docs/opengraph/
https://developers.facebook.com/docs/opengraph/getting-started/
https://developers.facebook.com/docs/opengraph/using-actions/
Keep in mind that it may take some hours or even some days until the Open Graph Actions are accepted by Facebook.
You can also publish Open Graph Actions in the background without user confirmation, as long as the user can change the publishing in a settings dialog, for example.

facebook Post on your behalf is not working in android facebook sdk 3.0.2

i am try to share the post in facebook. login, publish permission is working finefor the first time. if i delete the app from facebook web it is not asking me reinstalling login and "Post on your behalf" publish permission screen below is my code Please help what i made mistike. I tried lot but is not working properly.. Thank you for your kind advice and so i can improve lot in android. Below is my code...
public class FacebokView extends Activity {
static final String applicationId = String.valueOf(R.string.app_id);
Session session;
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;
private UiLifecycleHelper uiHelper;
//private StatusCallback statusCallback;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.faceok_view);
// create the session
this.session = createSession();
Log.i("session1--->", "session"+ session.isOpened());
// start Facebook Login
//Session.openActiveSession(this, true, new Session.StatusCallback() {
StatusCallback statusCallback = new StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state, Exception exception) {//READ
onSessionStateChange(session, state, exception);
Log.i("OPENED_TOKEN_UPDATED", state.equals(SessionState.OPENED_TOKEN_UPDATED) + "<<test");
if (session.isOpened() && session.getPermissions().contains("publish_actions")) {
Log.i("fb session1: publish_actions else if", session.getPermissions().contains("publish_actions") +"OPENED_TOKEN_UPDATED ----"+state.equals(SessionState.OPENED_TOKEN_UPDATED));
publishStory();
Log.i("session2--->", "session"+ session.isOpened());
} else if (session.isOpened()) {
Log.i("session3--->", "session"+ session.isOpened());
Log.i("fb session2: publish_actions else if", session.getPermissions().contains("publish_actions") +"OPENED_TOKEN_UPDATED ----"+state.equals(SessionState.OPENED_TOKEN_UPDATED));
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(FacebookView.this, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
}
} else if(session != null && session.getState() == SessionState.CLOSED_LOGIN_FAILED){
Log.i("fb session:", "not open");
Log.i("session4--->", "session"+ session.isOpened());
finish();
}
}
};
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)){
Log.i("session5--->", "session"+ session.isOpened());
session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
Log.i("CREATED_TOKEN_LOADED", "session"+ session.isOpened());
}else if (!session.isOpened() && !session.isClosed()) {
Log.i("session6--->", "session"+ session.isOpened());
OpenRequest req = new Session.OpenRequest(this);
req.setCallback(statusCallback);
session.openForRead(req);
} else {
Log.i("session7--->", "session"+ session.isOpened());
Session.openActiveSession(this, true, statusCallback);
}
}
private void onSessionStateChange(Session session, SessionState state,Exception exception) {
if (state.isOpened()) {
if (pendingPublishReauthorization && state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
Log.i("onSessionStateChange--->OPENED_TOKEN_UPDATED -->", state.equals(SessionState.OPENED_TOKEN_UPDATED) + "pendingPublishReauthorization-->" + pendingPublishReauthorization);
pendingPublishReauthorization = false;
publishStory();
Log.i("session12--->", "session"+ session.isOpened());
}
} else if (state.isClosed()) {
Log.i("session8--->", "session"+ session.isOpened());
// shareButton.setVisibility(View.INVISIBLE);
}
}
protected void publishStory() {
Session session = Session.getActiveSession();
if (session != null){
// Check for publish permissions
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(this, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
return;
}
// after login make request to the /me API
Bundle parameters = getIntent().getExtras();
String facebookResponse = parameters.getString("facebookResponse");
Log.i("fbResp from server 1 publish_actions:", session.getPermissions().contains("publish_actions") + "*---facebookResponse----*"+ facebookResponse);
try {
JSONObject jsonObj = new JSONObject(facebookResponse);
parameters.putString("message", jsonObj.getString("MsgForFb"));
parameters.putString("name", jsonObj.getString("NameForFb"));
parameters.putString("link", jsonObj.getString("LinkForFb"));
parameters.putString("Description", jsonObj.getString("DescForFb"));
parameters.putString("picture", jsonObj.getString("PicForFb"));
} catch (JSONException e1) {
e1.printStackTrace();
}
Request.Callback callback = new Request.Callback() {
public void onCompleted(Response response) {
if(response.getGraphObject() != null) {
Log.i("fb Response - ", response.toString());
JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
String postId = null;
try {
postId = graphResponse.getString("id");
} catch (JSONException e) {
e.printStackTrace();
Log.e("FacebookView: callBack:", "JSON error : " + e.getMessage());
}
FacebookRequestError error = response.getError();
if (error != null) {
Toast.makeText(FacebookView.this.getApplicationContext(), error.getErrorMessage(), Toast.LENGTH_LONG).show();
} else {
Log.i("FacebookView: Request.Callbak: postId = ", " "+postId);
}
}
}
};
Request request = new Request(session, "me/feed", parameters, HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
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) {
finish();
}
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
private Session createSession() {
Session activeSession = Session.getActiveSession();
if (activeSession == null || activeSession.getState().isClosed()) {
activeSession = new Session.Builder(this).setApplicationId(applicationId).build();
Session.setActiveSession(activeSession);
}
return activeSession;
}
private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
for (String string : subset) {
if (!superset.contains(string)) {
return false;
}
}
return true;
}
}
If the user deletes the app from Facebook, the only way your app will know is if you make a graph request, and it fails.
Here are some common strategies for handling errors - https://developers.facebook.com/docs/reference/api/errors/
You should also have a look at the Scrumptious sample that ships with the SDK, there's a handleError() method in SelectionFragment.java that implements the strategies outlined in the link above.

Activity result no fragment exists for index after facebook publish

I'm using Facebook sdk 3, and I have an fragment that has share button.
At first call it works.
At second call I got
06-24 10:24:47.430: W/FragmentActivity(2812): Activity result no fragment exists for index: 0x3face
After onActivityResult the fragment detached from the activity and I see the previous fragment from that activity.
Here is my code:
public class AboutFragment extends BaseFragment implements OnClickListener, Session.StatusCallback {
private static final String GA_CATEGORY = "About";
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private Button mShareEmailButton;
private Button mShareFacebookButton;
private Button mConatctUsButton;
private WebView mAboutText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View v = inflater.inflate(R.layout.fragment_about, container, false);
mShareEmailButton = (Button) v.findViewById(R.id.buttonShareEmail);
mShareFacebookButton = (Button) v.findViewById(R.id.buttonShareFacebook);
mConatctUsButton = (Button) v.findViewById(R.id.buttonContactUs);
mAboutText = (WebView) v.findViewById(R.id.webViewAbout);
mAboutText.loadUrl("file:///android_asset/about.html");
mShareEmailButton.setOnClickListener(this);
mShareFacebookButton.setOnClickListener(this);
mConatctUsButton.setOnClickListener(this);
return v;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonShareEmail:
GA_Handler.sendEvent(getActivity(), GA_CATEGORY, "Share_click", "Email");
shareViaEmail();
break;
case R.id.buttonShareFacebook:
GA_Handler.sendEvent(getActivity(), GA_CATEGORY, "Share_click", "FB");
checkFacebookLogin();
break;
case R.id.buttonContactUs:
GA_Handler.sendEvent(getActivity(), GA_CATEGORY, "Contact_us_click");
((BaseNavigationActivity)getActivity()).loadFragment(new ContactUsFragment());
break;
default:
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
boolean isFacebookResponse =
Session.getActiveSession().onActivityResult(getActivity(), requestCode, resultCode, data);
if (isFacebookResponse) {
System.out.println("FB Response");
}
}
/**
* Login to FB if needed
*/
public void checkFacebookLogin() {
try {
logInToFacebook();
} catch (Exception e) {
e.printStackTrace();
}
}
private void logInToFacebook() {
String app_id = getString(R.string.app_id);
Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
Session session = new Session.Builder(getActivity().getApplicationContext())
.setApplicationId(app_id)
.build();
session.addCallback(this);
Session.setActiveSession(session);
// Login
if (!session.isOpened() && !session.isClosed()) {
session.openForPublish(new Session.OpenRequest(this)
.setPermissions(PERMISSIONS)
.setCallback(this));
} else {
Session.openActiveSession(getActivity(), true, this);
}
}
#Override
public void call(Session session, SessionState state, Exception exception) {
System.out.println("ABOUT: " + state);
if (state == SessionState.OPENED) {
if(isAdded()){
publishFeedDialog();
}else{
System.out.println("Home activity not attached");
}
}
}
/**
* Publish to FB
*/
private void publishFeedDialog() {
Bundle params = new Bundle();
params.putString("name", getString(R.string.fb_share_name));
params.putString("caption", getString(R.string.fb_share_caption));
params.putString("description", getString(R.string.fb_share_description));
params.putString("link", getString(R.string.fb_share_link));
params.putString("picture", getString(R.string.fb_share_picture));
WebDialog feedDialog = (
new WebDialog.FeedDialogBuilder(getActivity(),
Session.getActiveSession(), params)) //
.setOnCompleteListener(new WebDialog.OnCompleteListener() {
Context appContext = getActivity().getApplicationContext();
#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) {
DebugToast.show(appContext, "Posted story, id: " + postId);
} else {
// User clicked the Cancel button
DebugToast.show(appContext, "Publish cancelled");
}
} else if (error instanceof FacebookOperationCanceledException) {
// User clicked the "x" button
DebugToast.show(appContext, "Publish cancelled");
} else {
// Generic, ex: network error
DebugToast.show(appContext, "Error posting story");
}
logOut();
}
})
.build();
feedDialog.show();
}
/**
* Disconnect from facebook
*/
public void logOut() {
Session session = Session.getActiveSession();
if (!session.isClosed()) {
session.closeAndClearTokenInformation();
}
}
}
How to make it work correct?
A different solution also accepted
Thanks in advance

android error with facebook login on market

When i test this app on my device with eclipse is all ok;but when i publish this app on google play store the facebook login failed!!
why?
help me please!!
it is a simply app ("coffee break" on market);
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main );
elementoInserito=(EditText)findViewById(R.id.editTextElementoInserito);
elementoEstratto=(TextView)findViewById(R.id.textViewElementoEstratto);
inserisci=(Button)findViewById(R.id.buttonInserisci);
stampa=(Button)findViewById(R.id.buttonStampa);
facebookLogin=(Button)findViewById(R.id.facebookLogin);
Session session = Session.getActiveSession();
if (session == null) {
if (savedInstanceState != null) {
session =Session.restoreSession(this,null,statusCallback,savedInstanceState);
}
if (session == null) {
session = new Session(this);
}
Session.setActiveSession(session);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
session.openForRead(newSession.OpenRequest(this).setCallback(statusCallback));
}
}
inserisci.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
inizializza_array(elementoInserito);
elementoInserito.setText("");
}
});
updateView();
}
private void updateView() {
Session session = Session.getActiveSession();
if (session.isOpened()) {
facebookLogin.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
onClickLogout(); }
});
}
else {
facebookLogin.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
onClickLogin(); }
});
}
}
private void onClickLogin() {
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
} else {
Session.openActiveSession(this, true, statusCallback);
}
Bundle bundle=new Bundle();
Session.saveSession(session,bundle);
Toast.makeText(getApplicationContext(),
"sto salvando la sessione "+session.getState(),
Toast.LENGTH_LONG).show();
}
private void onClickLogout() {
Session session = Session.getActiveSession();
if (!session.isClosed()) {
session.closeAndClearTokenInformation();
}
}
private class SessionStatusCallback implements Session.StatusCallback {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
updateView();
}
}
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
Log.i(TAG, "Logged in...");
} else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
}
}
public void inizializza_array(EditText n){
this.ins=""+n.getText();
if(ins==""){
Toast.makeText(getApplicationContext(),
"errore: campo vuoto",
Toast.LENGTH_LONG).show();
}
else{
lista.add(ins);
}
}
public void stampa(View v){
if(lista.size()==0){
elementoEstratto.setText("Inserire elementi");
}
else{
Random random = new Random();
String x = lista.get(random.nextInt(lista.size()));
elementoEstratto.setText(x);
lista.clear();
try {
publishStory(x);
} catch (Exception e) {
}
}
}
public void onStart() {
super.onStart();
Session.getActiveSession().addCallback(statusCallback);
}
#Override
public void onStop() {
super.onStop();
Session.getActiveSession().removeCallback(statusCallback);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
}
public void publishStory(String sorteggiato) {
Session session = Session.getActiveSession();
try {
if (session != null){
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new Session
.NewPermissionsRequest(this, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
return;
}
Bundle postParams = new Bundle();
postParams.putString("name",""));
postParams.putString("caption","");
postParams.putString("description","");
Request.Callback callback= new Request.Callback() {
public void onCompleted(Response response) {
JSONObject graphResponse = response
.getGraphObject()
.getInnerJSONObject();
String postId = null;
try {
postId = graphResponse.getString("id");
} catch (JSONException e) {
Log.i(TAG,
"JSON error "+ e.getMessage());
}
FacebookRequestError error = response.getError();
if (error != null) {
Toast.makeText(getApplicationContext(),
error.getErrorMessage(),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
"shared",//postId
Toast.LENGTH_LONG).show();
}
}
};
Request request = new Request(session, "me/feed", postParams,
HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
else{
Toast.makeText(getApplicationContext(),
"effettua il Login su Facebook per condividere con i tuo amici",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
// TODO: handle exception
}
}
private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
for (String string : subset) {
if (!superset.contains(string)) {
return false;
}
}
return true;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Intent intent = new Intent (MainActivity.this,Info.class);
//Intent intent2 = new Intent(MainActivity.this,Caffe.class);
menu.add("About Coffee Break").setIntent(intent);
//menu.add("Il caffè").setIcon(R.drawable.caffe).setIntent(intent2);
return true;
}
}
i don't understand why i've this problem
i've self resolved the problem, i did not read the relese.keystore in the rigth way
I did not understand this code:
keytool -exportcert -alias myAlias -keystore ~/.your/path/release.keystore | openssl sha1 -binary | openssl base64
when I realized the code I got the right key
myAlias = alis used when i export the project
~/.your/path/release.keystore = the path where the key generated from eclipse is located, and the name of the file
Good Job

Categories

Resources