Facebook SDK - how to override onActivityResult() correctly? - java

I have a simple Activity in which I want to get some information about the Facebook user:
public class FacebookActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.facebook_layout);
// start Facebook Login
Session.openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
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) {
Log.i("facebook_id", user.getId());
Log.i("facebook_name", user.getName());
}
}
});
}
}
});
}
}
But onCompleted() method is not called if the onActivityResult() method is not overridden. So, my question is how to make it correctly in my case?
Thanks.

try that
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode,
resultCode, data);
}

Related

How to use onActivityResult() in fragment?

In my application i want use InAppBillling for buy some features !
I write payment methods into fragment but after show payment dialog and pay by user not show me any data into onActivityResult!
I write log.e into onActivityResult, but again not show.
I think not going into onActivityResult!
My fragment codes :
public class ServicesFragment extends BaseFragment implements IabHelper.OnIabSetupFinishedListener,
IabHelper.QueryInventoryFinishedListener, IabHelper.OnIabPurchaseFinishedListener, IabHelper.OnConsumeFinishedListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_services, container, false);
...
}
#Override
public void onIabSetupFinished(IabResult result) {
if (iabHelper != null) {
iabHelper.flagEndAsync();
//This is call for payment
iabHelper.queryInventoryAsync(ServicesFragment.this);
}
}
#Override
public void onIabPurchaseFinished(IabResult result, final Purchase info) {
//After payment call this
if (result.isSuccess() && info != null) {
handler.post(new Runnable() {
#Override
public void run() {
getCheckBuyFromBazaar(jwtToken, packageName, productId, purchaseToken, buyID, 0, info);
}
});
}
}
#Override
public void onQueryInventoryFinished(IabResult result, Inventory inv) {
if (result.isSuccess()) {
bazaarProgressDialog.dismiss();
//Run bazaar dialog
if (iabHelper != null) {
iabHelper.flagEndAsync();
iabHelper.launchPurchaseFlow(activity, bazaarSKU, bazaarRequestCode,
ServicesFragment.this, bazaarHashCode);
}
}
}
#Override
public void onConsumeFinished(Purchase purchase, IabResult result) {
if (result.isSuccess() && purchase != null) {
if (purchase.getSku().equalsIgnoreCase(bazaarSKU)) {
//When purchase consumed
finishPage();
loadingProgressDialog.dismiss();
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.e("BazaarPaymentLog", "Result");
if (iabHelper == null) return;
if (requestCode == bazaarRequestCode) {
String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
if (resultCode == RESULT_OK) {
try {
JSONObject jo = new JSONObject(purchaseData);
purchaseToken = jo.getString("purchaseToken");
productId = jo.getString("productId");
packageName = jo.getString("packageName");
Log.e("BazaarPaymentLog", "purchaseToken : " + purchaseToken);
if (iabHelper != null) {
iabHelper.handleActivityResult(requestCode, resultCode, data);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
Show me payment dialog and i pay it, but after not going to onActivityResult!
I write above code into activity it's ok and run onActivityResult but into fragment not going into onActivityResult!
How can i fix it?
Actually the result is passed to Activity's onActivtyResult in order to get in Fragment's method you need to pass reult fron Activity to Fragment like below
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.frame);
fragment.onActivityResult(requestCode, resultCode, data);
}
and in Fragment call it same as you are calling currently
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
}
If you are using ViewPager you can get Fragment like below
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Fragment mFragment = myPagerAdapter.getItem(mViewPager.getCurrentItem());
if (fragment instanceof ServiccesFragment){
((ServiccesFragment)fragment).onActivityResult(requestCode, resultCode, data);
}
}

Login Facebook in android not working

I trying implements Facebook in my app Android but when a write my mail and password of Facebook no print "Dentro1" or "Dentro2" or "Dentro3". Why?
Thank you!!
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
System.out.println("Dentro1");
}
#Override
public void onCancel() {
System.out.println("Dentro2");
}
#Override
public void onError(FacebookException exception) {
System.out.println("Dentro3");
}
});
You need to do like below..
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
And..start login with some permissions what you want.
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("user_friends"));

facebook login fails: {Session state:CLOSED_LOGIN_FAILED, token:{AccessToken token:ACCESS_TOKEN_REMOVED permissions:[]}, appId:131***64547}

I try this code to perform login to my app using fb.
public class FacebookLogin2Activity extends BaseActivity {
private String TAG = "MainActivity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.facebook_login);
Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
fetchUserDetails(session);
}
LoginButton authButton = (LoginButton) findViewById(R.id.authButton);
authButton.setOnErrorListener(new OnErrorListener() {
#Override
public void onError(FacebookException error) {
Log.e(TAG, "Error " + error.getMessage());
}
});
// set permission list, Don't forget to add email
authButton.setReadPermissions(Arrays.asList("basic_info", "email",
"birthday"));
// option A
// Session.openActiveSession(this, true, new Session.StatusCallback() {
//
// // callback when session changes state
// #Override
// public void call(Session session, SessionState state,
// Exception exception) {
// fetchUserDetails(session);
// }
// });
// // option B
// session state call back event
authButton.setSessionStatusCallback(new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
fetchUserDetails(session);
}
}
});
}
private void fetchUserDetails(Session session) {
Log.i(TAG, "Access Token" + session.getAccessToken());
Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
//some code
}
}
}).executeAsync();
}
but i get this error
what should i check?
{Session state:CLOSED_LOGIN_FAILED, token:{AccessToken token:ACCESS_TOKEN_REMOVED permissions:[]}, appId:131390430364547}
and I have verified Facebook developers has my android hash code in the website.
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// start Facebook Login
Session.openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
TextView welcome = (TextView) findViewById(R.id.welcome);
welcome.setText("Hello " + user.getName() + "!");
}
}
});
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
}
There could be many possible reasons:
Wrong key hash. Generate one from the code provided by facebook:
PackageInfo info = getPackageManager().getPackageInfo("<your_package_name>", 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));
}
Make sure to replace "<your_package_name>" with your corresponding package name. Look at logcat and grab the keyhash and enter it in your facebook app settings.
Open the Facebook native app and make sure you are logged in properly and can access content. If you have incorrect credentials entered in the Facebook native app (perhaps you recently changed your password) then the Facebook SDK will repeatedly try to do an SSO using the native app and report back CLOSED_LOGIN_FAILED.
If you are using the Facebook application in the sandbox mode, make sure the account you are using is in the list of authorized admins or developers.
check your Manifest.xml
<meta-data android:value="#string/facebook_app_id" android:name="com.facebook.sdk.ApplicationId"/>
and your strings.xml have
<string name="facebook_app_id">131390430364547</string>
verify the app_id is the same in your facebook app configuration and set the "yourApp.mainactivity" in the Class field
is it the debbug app or released app? the hash code is diferent for each one
Edited *
for verify the status of the session
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
if (session.isOpened()) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Log.e("user", "session established");
Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
Log.e("user", "loged user");
buildUserInfoDisplay(user);
}
}
}).executeAsync();
}
else{
Log.e("user", "session not established");
}
}
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
}
};
and in the on create method to use the login button
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
uiHelper = new UiLifecycleHelper(this, callback);
uiHelper.onCreate(savedInstanceState);
setContentView(R.layout.login);
buttonLoginLogout = (LoginButton)findViewById(R.id.authButton);
buttonLoginLogout.setReadPermissions(Arrays.asList("user_status"));
}
}
also need to manage the ui status in al lifecycle methods
public void onResume() {
super.onResume();
uiHelper.onResume();
}
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
I have an app with this login exactly as i posted it, it wors good, facebook developer console is tracking the sessions of users. Try it !

an attempt was made to request new permissions for a session that has a pending request.Android

I have implemented fb integration and i am getting users details by setting some permissions but it is giving me error java.lang.UnsupportedOperationException: Session: an attempt was made to request new permissions for a session that has a pending request.
when i run first time and second time it it is not giving me this exception, i am using the latest fb SDK for integration. I'll post me code.
public class MainActivity extends Activity {
Button loginbtn;
Session session = Session.getActiveSession();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loginbtn = (Button)findViewById(R.id.loginbutton);
loginbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this,FacebookLogin.class);
startActivity(intent);
}
});
}
}
public class FacebookLogin extends Activity{
Session.NewPermissionsRequest newPermissionsRequest = new Session
.NewPermissionsRequest(this, Arrays.asList("email,user_birthday,user_location,user_hometown,user_about_me,user_relationships"));
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.facebooklogin);
Session.openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
#SuppressWarnings("deprecation")
#Override
public void call(final Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// Log.i("session.isOpened", "session.isOpened");
session.requestNewReadPermissions(newPermissionsRequest);
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
//session.requestNewReadPermissions(newPermissionsRequest);
//System.out.println("Response : "+response.toString());
Log.i("Response", response.toString());
if (user != null) {
Log.i("USERName", ""+user.getName());
Log.i("Birthday", ""+user.getBirthday());
Log.i("LastName", ""+user.getLastName());
Log.i("FirstName", ""+user.getFirstName());
Log.i("getId", ""+user.getId());
Log.i("email", " "+user.getLink()+" email : ) "+user.asMap().get("email"));
Log.i("location", ""+user.asMap().get("location"));
Log.i("gender", ""+user.asMap().get("gender"));
/* Intent i =new Intent(getApplicationContext(), MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);*/
finish();
}
}
});
}
}
});
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.i(" onResume()", "called");
};
#Override
public void onStart() {
Log.i(" onStart", "called");
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
#SuppressWarnings("deprecation")
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i("onActivityResult", "called");
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
final Session session = Session.getActiveSession();
if (session.isOpened()) {
session.requestNewReadPermissions(newPermissionsRequest);
// make request to the /me API
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) {
//session.requestNewReadPermissions(newPermissionsRequest);
Log.i("USERName2", ""+user.getName());
Log.i("Birthday2", ""+user.getBirthday());
Log.i("LastName2", ""+user.getLastName());
Log.i("FirstName2", ""+user.getFirstName());
Log.i("email2", " "+user.getLink()+" email : ) "+user.asMap().get("email"));
Log.i("location", ""+user.asMap().get("location"));
Log.i("gender", ""+user.asMap().get("gender"));
/* Intent i =new Intent(getApplicationContext(), MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
finish();*/
//Log.i("USERName", ""+user.getName());
}
}
});
}else {
finish();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
Log.i("onSaveInstanceState", "called");
super.onSaveInstanceState(outState);
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
}
}
Update the Active Session using onActivityResult method.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}

android facebook login Graphuser details

i have a buttonLoginLogout Button which is a facebook login button (i imported the facebook sdk into my project) and this is my methods in my mainActivity:
its takes from LoginUsingActivityActivity sample from facebook activity, i didnt see a GraphUser or oncompleted mehod, so how can i get the user detailes that connected via facebook...
i tried to add "void onCompleted" method (in the end as you can see), however i cant override it and i cant get the user details, and when i login to facebook (and the login succeed) it doesnt get to the oncompleted method...
how can i get the GraphUser that logged into facebook successfully?
Also, i added the onCompleted method here, it wasn't here and it says that it is not override another moethod..
thanks alot
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();
if (session.isOpened()) {
//button logout string
buttonLoginLogout.setOnClickListener(new OnClickListener() {
public void onClick(View view) { onClickLogout(); }
});
} else {
//button log in string
buttonLoginLogout.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);
}
}
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) {
updateView();
}
//doesnt get here, why?????????
public void onCompleted(GraphUser user, Response response) {
}
}
write this in a method:
final Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
// If the session is open, make an API call to get user data
// and define a new callback to handle the response
Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
// If the response is successful
if (session == Session.getActiveSession()) {
if (user != null) {
user_ID = user.getId();//user id
profileName = user.getName();//user's profile name
userNameView.setText(user.getName());
}
}
}
});
Request.executeBatchAsync(request);
}
and make sure that this method is called only after a successfully login. that mean u should call it from the onActivityResult.

Categories

Resources