How to get UserData for facebook from this code? - android

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)");
}

Related

Unable show poup login when I login facebook second times in android

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!!!!

how to go to another activity after successful login to Facebook in android?

I have integrated Facebook in my Android App using Sessions. I have a Login Activity that has a button for Facebook login. I want to go to another activity called MainActivity after successful login to successful login in Facebook the app closes without any error or without going to the MainActivity. Can anyone suggest me where I should give the code to start the activity. Here is my code.
ImageButton buttonLoginLogout,bb;
Session.StatusCallback statusCallback = new SessionStatusCallback();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
buttonLoginLogout = (ImageButton)findViewById(R.id.imageButton1);
buttonLoginLogout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
onClickLogin();
}
});
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));
}
}
updateView();
}
#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);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
}
private void updateView() {
Session session = Session.getActiveSession();
}
});
Intent ik=new Intent(Login.this,MainActivity.class);
startActivity(ik);
} }
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);
}
}
private class SessionStatusCallback implements Session.StatusCallback {
#Override
public void call(Session session, SessionState state, Exception exception) {
updateView();
}
}
}
Do it like this.
protected void onPostExecute(Bitmap bm){
//Drawable drawable = new BitmapDrawable(getResources(), bm);
Bitmap b1=bm;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
b1.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
// Log.w("bit",""+drawable);
String encodedImage = Base64.encodeToString(b,Base64.DEFAULT);
Editor edit=pref.edit();
edit.putString("image_data",encodedImage);
edit.commit();
Intent ik=new Intent(Login.this,MainActivity.class);
startActivity(ik);
}
};
t.execute();
Just move your
Intent ik=new Intent(Login.this,MainActivity.class);
startActivity(ik);
this code inside postexecute method.

How to get the user info. using the android facebook sdk?

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);
}
}
});

Can't start another activity after Facebook login in android app

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..

Facebook login fails with facebook app installed

I'm new to android development. I've downloaded facebook sdk 3.0.1, and using the sample code to log in. The problem is, that if facebook app is installed the authentication fails.
(otherwise it works just fine)
after pressing the log in button I get to onActivityResult with status CLOSED_LOGIN_FAILED.
of course I'm not typing the password, it's done automatically through facebook's app, and the facebook app is logged in and works properly.
I couldn't find a solution..
please help me :)
this is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
instance = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonLoginToFacebook = (Button) findViewById(R.id.buttonLoginToFacebook);
tvWellcome = (TextView) findViewById(R.id.tvWellcome);
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));
}
}
updateView();
}
#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);
updateView();
}
#Override
protected 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()) {
Intent intent = new Intent(this, ScreenStartPage.class);
startActivity(intent);
} else {
buttonLoginToFacebook.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));
updateView();
} else {
Session.openActiveSession(this, true, statusCallback);
}
}
public 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) {
updateView();
}
}
Have you setup your debug key hash and full class name on Facebook's app settings dashbaord? see steps 5 and 6 in the Getting Started with the Facebook SDK for Android doc.

Categories

Resources