if (state.isOpened()) {
// Request user data and show the results
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
// Display the parsed user info
}
}
});
}
I have tried follow the facebook doc to get the user info when at the onSessionStateChange function, the problem is , it is weird that I follow the offical doc and it shows
Request.executeMeRequestAsync is depreciate , so I wonder how to implement get the user info in latest facebook sdk 3.6 ? What I would like to do is get the user info if the user logined. Thanks a lot
Update:
Anyway I would also like to ask whether this way to implement login is correct? There are two place in my app need to login
The first one is inside a fragment
public class Home extends Fragment {
public View rootView;
public ImageView HomeBg;
public ImageView buttonLoginLogout;
public TextView chi;
public TextView eng;
public ColorStateList oldColor;
public SharedPreferences prefs;
public EasyTracker tracker = null;
//Facebook login
private Session.StatusCallback statusCallback = new SessionStatusCallback();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
tracker = EasyTracker.getInstance(getActivity());
getActivity().getActionBar().hide();
rootView = inflater.inflate(R.layout.home, container, false);
buttonLoginLogout = (ImageView) rootView.findViewById(R.id.home_connectFB);
eng = (TextView) rootView.findViewById(R.id.btn_eng);
chi = (TextView) rootView.findViewById(R.id.btn_chi);
if (Utility.getLocale(getActivity()).equals("TC")) {
chi.setTextColor(getActivity().getResources().getColor(
android.R.color.white));
oldColor = eng.getTextColors();
} else {
eng.setTextColor(getActivity().getResources().getColor(
android.R.color.white));
oldColor = chi.getTextColors();
}
eng.setOnClickListener(setChangeLangListener("EN"));
chi.setOnClickListener(setChangeLangListener("TC"));
//Facebook login
Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
Session session = Session.getActiveSession();
if (session == null) {
if (savedInstanceState != null) {
session = Session.restoreSession(getActivity(), null, statusCallback, savedInstanceState);
}
if (session == null) {
session = new Session(getActivity());
}
Session.setActiveSession(session);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
}
}
updateView();
return rootView;
}
#Override
public void onStart() {
super.onStart();
Session.getActiveSession().addCallback(statusCallback);
tracker.set(Fields.SCREEN_NAME, "Landing Page " + Utility.getLocale(getActivity()));
tracker.send(MapBuilder.createAppView().build());
}
#Override
public void onStop() {
super.onStop();
Session.getActiveSession().removeCallback(statusCallback);
EasyTracker.getInstance(getActivity()).activityStop(getActivity());
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(getActivity(), requestCode, resultCode, data);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
}
private void updateView() {
Session session = Session.getActiveSession();
if (session.isOpened()) {
buttonLoginLogout.setImageResource(R.drawable.landing_btn_take_a_selfie);
buttonLoginLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
((LandingPage)getActivity()).tabHost.setCurrentTab(2);
}
});
} else {
buttonLoginLogout.setImageResource(R.drawable.landing_btn_connect_facebook);
buttonLoginLogout.setOnClickListener(new View.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(getActivity(), this, true, statusCallback);
}
}
private class SessionStatusCallback implements Session.StatusCallback {
#Override
public void call(Session session, SessionState state, Exception exception) {
updateView();
}
}
public OnClickListener setChangeLangListener(final String lang) {
OnClickListener changeLangListener = new OnClickListener() {
#Override
public void onClick(View arg0) {
Configuration config = new Configuration(getResources().getConfiguration());
if (Utility.getLocale(getActivity()).equals("TC") && lang.equals("EN")) {
tracker.send(MapBuilder.createEvent("menu_click","language", "switchEN", null).build());
config.locale = Locale.ENGLISH;
chi.setTextColor(oldColor);
eng.setTextColor(getActivity().getResources().getColor(
android.R.color.white));
} else if (Utility.getLocale(getActivity()).equals("EN") && lang.equals("TC")) {
tracker.send(MapBuilder.createEvent("menu_click","language", "switchTC", null).build());
config.locale = Locale.TRADITIONAL_CHINESE;
eng.setTextColor(oldColor);
chi.setTextColor(getActivity().getResources().getColor(
android.R.color.white));
}
getResources().updateConfiguration(config,getResources().getDisplayMetrics());
onConfigurationChanged(config);
}
};
return changeLangListener;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Intent intent = getActivity().getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
getActivity().finish();
startActivity(intent);
}
#Override
public void onResume() {
super.onResume();
AppEventsLogger.activateApp(getActivity(),getResources().getString(R.string.app_id));
}
}
The other one is inside another activity
public class SharePicForm extends Activity {
private final String TAG = "SharePicForm";
public ImageView photoArea;
public ImageView sharePhotoBtn;
public EditText shareContent;
public Bitmap mBitmap;
public Context ctx;
public String shareTxt;
public String fileUri;
public static boolean isShowForm = true;
public ProgressDialog pd;
public EasyTracker tracker = null;
//Facebook share
private PendingAction pendingAction = PendingAction.NONE;
private enum PendingAction {
NONE, POST_PHOTO
}
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tracker = EasyTracker.getInstance(this);
setContentView(R.layout.share_pic_form);
ctx = this;
Utility.setHeader(this,R.string.selfie_header,false);
Session session = Session.getActiveSession();
if (session == null) {
if (savedInstanceState != null) {
session = Session.restoreSession(this, null, callback, savedInstanceState);
}
if (session == null) {
session = new Session(this);
}
Session.setActiveSession(session);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
session.openForRead(new Session.OpenRequest(this).setCallback(callback));
}
}
photoArea = (ImageView) findViewById(R.id.photo_area);
shareContent = (EditText) findViewById(R.id.share_content);
if (getIntent() != null) {
Intent intent = getIntent();
fileUri = (String) intent.getStringExtra("photo");
} else if (savedInstanceState != null){
mBitmap = (Bitmap) savedInstanceState.getParcelable("bitmap") == null ? null : (Bitmap) savedInstanceState.getParcelable("bitmap");
}
FileInputStream inputStream;
try {
File imgSelected = new File(fileUri);
if (imgSelected.exists()) {
inputStream = new FileInputStream(imgSelected);
mBitmap = Utility.decodeBitmap(inputStream, 1280, 960);
photoArea.setImageBitmap(mBitmap);
sharePhotoBtn = (ImageView) findViewById(R.id.share_submit);
sharePhotoBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mBitmap != null && FormValidation.hasText(shareContent)) {
try {
File imageToShare = saveBitmapToStorage();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
shareTxt = shareContent.getText().toString();
performPublish(PendingAction.POST_PHOTO);
//new FormSubmit(ctx,easyTracker).execute("shareImg",imageToShare, textToShare);
}
}
});
} else {
Toast.makeText(ctx, ctx.getResources().getString(R.string.get_photo_error), Toast.LENGTH_SHORT).show();
finish();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private File saveBitmapToStorage () throws IOException{
String path = Environment.getExternalStorageDirectory().toString();
File outputFile = new File(path, "temp.jpg");
FileOutputStream out = new FileOutputStream(outputFile);
mBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
return outputFile;
}
//Facebook share
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (pendingAction != PendingAction.NONE &&
(exception instanceof FacebookOperationCanceledException ||
exception instanceof FacebookAuthorizationException)) {
new AlertDialog.Builder(SharePicForm.this)
.setTitle(ctx.getResources().getString(R.string.error))
.setMessage(ctx.getResources().getString(R.string.get_permission_error))
.setPositiveButton(ctx.getResources().getString(R.string.close), null)
.show();
pendingAction = PendingAction.NONE;
} else if (state == SessionState.OPENED_TOKEN_UPDATED) {
handlePendingAction();
}
}
private boolean hasPublishPermission() {
Session session = Session.getActiveSession();
return session != null && session.getPermissions().contains("publish_actions");
}
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;
if (previouslyPendingAction == PendingAction.POST_PHOTO)
postPhoto();
}
private void performPublish(PendingAction action) {
Log.d(TAG,"Perform publish");
Session session = Session.getActiveSession();
if (session != null) {
Log.d(TAG,"Session != null");
pendingAction = action;
if (hasPublishPermission()) {
Log.d(TAG,"Has permission");
// We can do the action right away.
handlePendingAction();
return;
} else if (session.isOpened()) {
Log.d(TAG,"Open session");
// We need to get new permissions, then complete the action when we get called back.
session.requestNewPublishPermissions(new Session.NewPermissionsRequest(this, "publish_actions"));
return;
} else {
onClickLogin();
}
} else{
Log.d(TAG,"Session == null");
}
}
private void onClickLogin() {
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
session.openForRead(new Session.OpenRequest(this).setCallback(callback));
} else {
Session.openActiveSession(this, true, callback);
}
}
private void postPhoto() {
Log.d(TAG,"postPhoto: " + hasPublishPermission());
if (hasPublishPermission()) {
if (mBitmap != null) {
Request request = Request.newUploadPhotoRequest(
Session.getActiveSession(),mBitmap, new Request.Callback() {
#Override
public void onCompleted(Response response) {
pd.dismiss();
if (response.getError() == null) {
Utility.showDialog(ctx,"success_photo",tracker);
} else {
Log.d(TAG,response.getError().getErrorMessage());
Toast.makeText(ctx, response.getError().getErrorMessage(), Toast.LENGTH_LONG).show();
Utility.showDialog(ctx,"error",tracker);
}
}
});
Bundle params = request.getParameters();
if (shareTxt != null)
params.putString("message", shareTxt);
request.setParameters(params);
request.executeAsync();
pd = ProgressDialog.show(ctx, ctx.getResources().getString(R.string.sys_info),ctx.getResources().getString(R.string.publishing));
}
} else {
pendingAction = PendingAction.POST_PHOTO;
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("bitmap", mBitmap);
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
}
#Override
public void onStart() {
super.onStart();
Session.getActiveSession().addCallback(callback);
EasyTracker.getInstance(this).activityStart(this);
tracker.set(Fields.SCREEN_NAME, "Image_entryForm " + Utility.getLocale(this));
tracker.send(MapBuilder.createAppView().build());
}
#Override
public void onStop() {
super.onStop();
Session.getActiveSession().removeCallback(callback);
EasyTracker.getInstance(this).activityStop(this);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
#Override
public void onResume() {
super.onResume();
AppEventsLogger.activateApp(this,getResources().getString(R.string.app_id));
}
}
Should I implement the get user info code in all activities? thanks
Okay, Use below code.
//Define textview to print detail
TextView mfirstname, mlastname, middlename, mfullname, mbirthdate,
mfacebookLink, mfacebookId, mfacebookUnm, mgender, mEmail;
// Code to retrieve data from FB
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.executeMeRequestAsync(session,
new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user,
Response response) {
if (user != null) {
mfirstname.setText(user.getFirstName());
mlastname.setText(user.getLastName());
middlename.setText(user.getMiddleName());
mfullname.setText(user.getName());
mbirthdate.setText(user.getBirthday());
mfacebookLink.setText(user.getLink());
mfacebookId.setText(user.getId());
mfacebookUnm.setText(user.getUsername());
String gender = user.asMap()
.get("gender").toString();
String email = user.asMap()
.get("email").toString();
mgender.setText(gender);
mEmail.setText(email);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
} else {
Toast.makeText(getApplicationContext(), "Error...",
Toast.LENGTH_LONG);
}
}
});
Related
Here is my code for login in facebook:
private boolean isFirstTime;
private CustomProgressDialog customProgressDialog;
private Session.StatusCallback statusCallback = new SessionStatusCallback();
private String fbEmail;
private String fbName;
private String fbToken;
private String id;
private String avatar;
private LoginView mView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
isFirstTime = true;
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);
}
Session.getActiveSession().addCallback(statusCallback);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback).setPermissions(
Arrays.asList("email", "user_likes", "user_status")));
}
mView = new LoginView(this);
mView.imgLoginFaceBook.setOnClickListener(this);
mView.rllLoginSkip.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == mView.imgLoginFaceBook) {
facebookLogin();
}
if (v == mView.rllLoginSkip) {
ReplaceToPage.ReplaceToHome(this);
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
private void facebookLogin() {
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
Session.OpenRequest request = new Session.OpenRequest(this);
request.setPermissions(Arrays.asList("email"));
request.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);
session.openForRead(request.setCallback(statusCallback));
} else {
Session.openActiveSession(this, true, statusCallback);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
}
#Override
public void onStart() {
super.onStart();
Session.getActiveSession().addCallback(statusCallback);
Session session = Session.getActiveSession();
}
#Override
public void onStop() {
super.onStop();
Session.getActiveSession().removeCallback(statusCallback);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
#SuppressWarnings("deprecation")
private void updateFacebookView() {
final Session session = Session.getActiveSession();
if (isFirstTime) {
isFirstTime = false;
return;
}
if (session.isOpened()) {
Log.d("access token", session.getAccessToken());
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) {
if (user.asMap().toString().contains("email")) {
fbEmail = user.asMap().get("email").toString();
fbToken = user.asMap().get("id").toString();
Globals.FBToken = fbToken;
fbName = user.asMap().get("last_name").toString();
Globals.name = user.getName();
id = user.getId();
String idd = user.getId();
avatar = "http://graph.facebook.com/" + id + "/picture?type=large";
Log.i("avatar", avatar);
ACCUtils.setStringPreferences(getApplicationContext(), "", avatar);
ReplaceToPage.ReplaceToHome(LoginActivity.this);
} else {
session.closeAndClearTokenInformation();
return;
}
}
}
});
}
}
private class SessionStatusCallback implements Session.StatusCallback {
#Override
public void call(Session session, SessionState state, Exception exception) {
updateFacebookView();
}
}
Here is my code for logout:
Session session = Session.getActiveSession();
if (session != null) {
if (!session.isClosed()) {
session.closeAndClearTokenInformation();
}
}
ACCUtils.setStringPreferences(getApplicationContext(), "", "");
Globals.FBToken = "";
The first login was woking good, but when I logout and login again, it doesn't show popup and allow app login from fb. I want to show popup, help me!!!!
public class MainActivity extends Activity {
private GraphUser user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setupFacebookConnect(savedInstanceState);
Button facebook_connect = (Button) findViewById(R.id.loginButton);
facebook_connect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (isFacebookConnected()) {
disConnectFacebook();
} else {
connectFacebook();
getProfileInformation(user);
}
}
});
}
private Session.StatusCallback statusCallback = new FBSessionStatus();
public void setupFacebookConnect(Bundle savedInstanceState) {
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)) {
session.openForRead(new Session.OpenRequest(this)
.setCallback(statusCallback));
}
}
}
public boolean isFacebookConnected() {
Session session = Session.getActiveSession();
return (session.isOpened()) ? true : false;
}
public void connectFacebook() {
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
session.openForRead(new Session.OpenRequest(this)
.setCallback(statusCallback));
} else {
Session.openActiveSession(this, true, statusCallback);
}
}
#Override
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);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode,
resultCode, data);
}
public class FBSessionStatus implements Session.StatusCallback {
#Override
public void call(Session session, SessionState state,
Exception exception) {
}
}
public void disConnectFacebook() {
Session session = Session.getActiveSession();
if (!session.isClosed()) {
session.closeAndClearTokenInformation();
}
}
And here is my code to fetch information:
public void getProfileInformation(GraphUser user) {
Session session = Session.getActiveSession();
boolean enableButtons = (session != null && session.isOpened());
MainActivity.this.user = user;
TextView showName = (TextView) findViewById(R.id.showName);
if (enableButtons && user != null) {
showName.setText("Hello, " + user.getLastName());
} else {
showName.setText("Connect to sign up (or log in)");
}
}
}
When I run the code it says only "Connect to sign up (or log in)" option.
I dont know where am I missing to get user information ?
Can anybody help ?
Well, i managed with this finally.
if (enableButtons && user != null) {
showName.setText("Hello, " + user.getLastName());
Intent i = new Intent(this, NextPage.class);
i.putExtra("name",user.getName());
} else {
showName.setText("Connect to sign up (or log in)");
}
I have tried a lot to integrate facebook login in my android app. I have succeeded partially. Now my problem is I couldn't redirect to another activity after successful facebook login. I think it is because I called the activity not from a proper place. I mean I coudn't call activity before the session close. I have attached my code here.
public class FacebookLogin extends Activity {
private static List<String> permissions;
Session.StatusCallback statusCallback = new SessionStatusCallback();
ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LoginButton authButton = (LoginButton) findViewById(R.id.authButton);
// authButton.setFragment(this);
/***** FB Permissions *****/
permissions = new ArrayList<String>();
permissions.add("email");
/***** End FB Permissions *****/
authButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Check if there is any Active Session, otherwise Open New Session
Session session = Session.getActiveSession();
if(!session.isOpened()) {
session.openForRead(new Session.OpenRequest(FacebookLogin.this).setCallback(statusCallback).setPermissions(permissions));
} else {
Session.openActiveSession(FacebookLogin.this, true, statusCallback);
}
}
});
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);
session.addCallback(statusCallback);
if(session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback).setPermissions(permissions));
}
}
}
private class SessionStatusCallback implements Session.StatusCallback {
#Override
public void call(Session session, SessionState state, Exception exception) {
//Check if Session is Opened or not
processSessionStatus(session, state, exception);
}
}
#SuppressWarnings("deprecation")
public void processSessionStatus(Session session, SessionState state, Exception exception) {
if(session != null && session.isOpened()) {
if(session.getPermissions().contains("email")) {
//Show Progress Dialog
dialog = new ProgressDialog(FacebookLogin.this);
dialog.setMessage("Loggin in..");
dialog.show();
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (dialog!=null && dialog.isShowing()) {
dialog.dismiss();
}
if(user != null) {
Map<String, Object> responseMap = new HashMap<String, Object>();
GraphObject graphObject = response.getGraphObject();
responseMap = graphObject.asMap();
Log.i("FbLogin", "Response Map KeySet - " + responseMap.keySet());
// TODO : Get Email responseMap.get("email");
String fb_id = user.getId();
String email = null;
String name = (String) responseMap.get("name");
if (responseMap.get("email")!=null) {
email = responseMap.get("email").toString();
//TODO Login successfull Start your next activity
Intent intent = new Intent(FacebookLogin.this, UserAccount.class);
/*Sending some arguments*/
Bundle bundle = new Bundle();
bundle.putString("UserName",name );
bundle.putString("Id", email);
intent.putExtras(bundle);
startActivity(intent);
}
else {
//Clear all session info & ask user to login again
Session session = Session.getActiveSession();
if(session != null) {
session.closeAndClearTokenInformation();
}
}
}
}
});
} else {
session.requestNewReadPermissions(new Session.NewPermissionsRequest(FacebookLogin.this, permissions));
}
}
}
/********** Activity Methods **********/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("FbLogin", "Result Code is - " + resultCode +"");
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
/*if(resultCode==RESULT_OK) {
Intent i = new Intent(FacebookLogin.this,UserAccount.class);
startActivity(i);
} */}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Save current session
super.onSaveInstanceState(outState);
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
}
#Override
protected void onStart() {
// TODO Add status callback
super.onStart();
Session.getActiveSession().addCallback(statusCallback);
}
#Override
protected void onStop() {
// TODO Remove callback
super.onStop();
Session.getActiveSession().removeCallback(statusCallback);
}
Please help me..
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
My app is having Share button to share story on users timeline. What I'm doing is, user taps on Share button, if user session is not present app forces to Login user with Facebook.
When user do that, story directly need to be published. Here's my code.
onCreate Method
isShared = false;
uiHelper = new UiLifecycleHelper(this, statusCallback);
uiHelper.onCreate(savedInstanceState);
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)) {
session.openForRead(new Session.OpenRequest(this)
.setCallback(statusCallback));
}
}
if (savedInstanceState != null) {
pendingPublishReauthorization = savedInstanceState.getBoolean(
PENDING_PUBLISH_KEY, false);
}
shareBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
doPostStory();
}
});
And remaining code is -
private void doPostStory() {
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
session.openForRead(new Session.OpenRequest(this)
.setCallback(statusCallback));
} else {
isShared = true;
Session.openActiveSession(this, true, statusCallback);
publishStory();
}
}
private class SessionStatusCallback implements Session.StatusCallback {
#Override
public void call(Session session, SessionState state,
Exception exception) {
if(!isShared){
updateView();
isShared = true;
}
}
}
private void updateView() {
Session session = Session.getActiveSession();
if (session.isOpened()) {
if(!isShared){
publishStory();
}
Log.i("Session State callback", "Logged in");
} else {
Log.i("Session State Callback", "Logged Out");
}
}
#Override
public void onStart() {
super.onStart();
Session.getActiveSession().addCallback(statusCallback);
}
#Override
public void onStop() {
super.onStop();
Session.getActiveSession().removeCallback(statusCallback);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode,
resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
outState.putBoolean(PENDING_PUBLISH_KEY, pendingPublishReauthorization);
uiHelper.onSaveInstanceState(outState);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onResume() {
super.onResume();
uiHelper.onResume();
}
Code for publishStory()
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", "Some");
postParams.putString("caption",updateTitle);
postParams.putString("description",updateText);
postParams.putString("link","http://somedomain.com");
postParams.putString("picture","someurl");
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("asd", "JSON error " + e.getMessage());
}
FacebookRequestError error = response.getError();
if (error != null) {
Toast.makeText(UpdateDetails.this,
error.getErrorMessage(), Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(UpdateDetails.this, postId,
Toast.LENGTH_LONG).show();
}
}
};
Request request = new Request(session, "me/feed", postParams,
HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
} else {
Log.i("Session Sate", "close");
}
}
Code does post story on users timeline. But it is posting multiple times. That means, statusCallbackgetting fired multiple times. I tried setting flags to check status of story post. But still it post several times.
Any ideas what's wrong with this code ? Help is highly appreciated.
PS : I don't need Login Button separately. What I want is, user taps on Share button, if logged in it need to post story else log in user and next directly post the story.
remove all the publishStory() calling. in your callback do this:
public void call(Session session, SessionState state,
Exception exception) {
if(session != null && session.isOpened() && isShared){
publishStory();
}
}
in your UpdateDetails class declare isShared as boolean isShared = false;
and when user tap on share button make it true, like:
shareBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
isShared = true;
doPostStory();
}
});
in your publishStorys onComplete make isShared false. like:
public void onCompleted(Response response) {
isShared = false;
...................
...................
}
hope this will help.
Create Facebook Session Object
Then Just Apply This in onCreate Method.
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.newMeRequest(session,
new Request.GraphUserCallback() {
// callback after Graph API response with user
// object
#Override
public void onCompleted(GraphUser user,
Response response) {
FacebookLoginActivity.this.progressDialog = ProgressDialog
.show(YourActivity.this,
"",
"",
true);
if (user != null) {
Intent passIntent = new Intent(YourActivity.this,Second.class)
startActivity(passIntent)
}
}
}).executeAsync();
}
}
});