Reputation: 1504
I integrated facebook sharing, It was working fine from last few days, but today just 2 hours before asking this question I am facing this issue.
I am using this code for Login :
Session.openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
@Override
public void call(Session session, SessionState state, Exception exception) {
if (state.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) {
if (user != null) {
Toast.makeText(ImagePagerActivity.this, user.getName()+" Logged In...", Toast.LENGTH_LONG).show();
}
}
}).executeAsync();
}
}
});
publishFeedDialog();
The problem is in if() condition which is always false, also I used session.isOpened()
which is also returning false, I am confused why this happened.
I have declared INTERNET,ACCESSNETWORKSTATE, permission in manifest also
<application>
..........
..........
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/app_id"/>
</application>
please help...
EDIT
This is the code of what I have implemented, you can see onCreateOptionsMenu
, onOptionsItemSelected
, onActivityResult
, publishFeedDialog
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.action_bar_share_menu, menu);
MenuItem item = menu.findItem(R.id.menu_item_share1);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_share1: // facebook item selected
Toast.makeText(this, "Menu Item 1 selected", Toast.LENGTH_SHORT).show();
//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 (state.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) {
if (user != null) {
Toast.makeText(ImagePagerActivity.this, user.getName()+" Logged In...", Toast.LENGTH_LONG).show();
}
}
}).executeAsync();
}
}
});
publishFeedDialog();
}
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data, new FacebookDialog.Callback() {
@Override
public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data) {
Log.e("Activity", String.format("Error: %s", error.toString()));
}
@Override
public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) {
Log.i("Activity", "Success!");
}
});
}
@Override
protected void onResume() {
super.onResume();
uiHelper.onResume();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(STATE_POSITION, pager.getCurrentItem());
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
@Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
private void publishFeedDialog() {
Log.v("pos",""+pos);
Bundle params = new Bundle();
params.putString("name", ItemListApplication.names.get(pos).getItem());
params.putString("caption", "Irrational beliefs");
params.putString("description",ItemListApplication.names.get(pos).getDesc() );
params.putString("link", "https://www.facebook.com/vivek.warde.3?ref=tn_tnmn");
if(pos==0) params.putString("picture","http://i.imgur.com/lOIUcW2.jpg");
else params.putString("picture",imageUrls[pos]);
WebDialog feedDialog = (
new WebDialog.FeedDialogBuilder(this,
Session.getActiveSession(),
params))
.setOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(Bundle values,
FacebookException error) {
if (error == null) {
// When the story is posted, echo the success
// and the post Id.
final String postId = values.getString("post_id");
if (postId != null) {
Toast.makeText(ImagePagerActivity.this,
"Posted story, id: "+postId,
Toast.LENGTH_SHORT).show();
} else {
// User clicked the Cancel button
Toast.makeText(ImagePagerActivity.this,
"Publish cancelled",
Toast.LENGTH_SHORT).show();
}
} else if (error instanceof FacebookOperationCanceledException) {
// User clicked the "x" button
Toast.makeText(ImagePagerActivity.this,
"Publish cancelled",
Toast.LENGTH_SHORT).show();
} else {
// Generic, ex: network error
Toast.makeText(ImagePagerActivity.this,
"Error posting story",
Toast.LENGTH_SHORT).show();
}
}
})
.build();
feedDialog.show();
}
Upvotes: 3
Views: 3507
Reputation: 5121
**generate keyhash from facebook api and then**
running this in to commandprompt/ terminal
keytool -exportcert -alias YOUR_ALIAS_NAME -keystore PATH_TO_KEYSTORE_FILE | openssl sha1 -binary | openssl base64
in Android.Manifest file
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="@string/app_id" />
in demofacebookLogin ( Activity file )
private Facebook facebook;
private AsyncFacebookRunner mAsyncRunner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
facebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
}
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_stream" },
new DialogListener() {
@Override
public void onCancel() {
// Function to handle cancel event
}
@Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
getProfileInformation();
}
@Override
public void onError(DialogError error) {
// Function to handle error
}
@Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
@Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
JSONObject profile = new JSONObject(json);
// getting name of the user
facebook_FB_Id = profile.getString("id");
facebook_username = profile.getString("name");
// getting email of the user
facebook_email = profile.getString("email");
facebook_firstname = profile.getString("first_name");
facebook_lastname = profile.getString("last_name");
facebook_FbLink = profile.getString("link");
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.i("", facebook_FB_Id + " == "
+ facebook_username + " =="
+ facebook_FbLink);
Intent startRegistrationTypeActivity = new Intent(
getContext(),
RegistrationTypeActivity.class);
startRegistrationTypeActivity.putExtra(
"facebook_FB_Id", facebook_FB_Id);
startRegistrationTypeActivity.putExtra(
"facebook_username", facebook_username);
startRegistrationTypeActivity.putExtra(
"facebook_email", facebook_email);
startRegistrationTypeActivity.putExtra(
"facebook_firstname", facebook_firstname);
startRegistrationTypeActivity.putExtra(
"facebook_lastname", facebook_lastname);
startRegistrationTypeActivity.putExtra(
"facebook_FbLink", facebook_FbLink);
startActivity(startRegistrationTypeActivity);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onIOException(IOException e, Object state) {
}
@Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
@Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
@Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}
Upvotes: 0
Reputation: 4257
It can be many reasons dealing with this problem. You should check some of this:
I'm using this code for login via facebook:
class MyFragment extends Fragment {
//... some code
SessionStatusCallback statusCallback = new SessionStatusCallback();
public void login() {
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) {
if (exception != null) {
handleException(exception);
}
if (state.isOpened()) {
afterLogin();
} else if (state.isClosed()) {
afterLogout();
}
}
}
}
If session wasn't opened you should open it for read (or for publish if you need).
Check meta-data
tag in AndroidManifest file, is there correct application id?
Often happens that error not inside android application but in facebook application settings. In facebook application's settings page should be correct package name, and you should add key hashes for you application (different for every release type, in most cases is debug and release).
To get hash key you can run script
keytool -exportcert -alias YOUR_ALIAS -keystore PATH_TO_KEYSTORE_FILE | openssl sha1 -binary | openssl base64
or you can get it inside code:
PackageInfo info;
try {
info = getPackageManager().getPackageInfo("YOUR_APP_PACKAGE", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md;
md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String keyhash = new String(Base64.encode(md.digest(), 0));
//string something is what you should paste as key hash
Log.e("hash key", keyhash);
}
} catch (NameNotFoundException e1) {
Log.e("name not found", e1.toString());
} catch (NoSuchAlgorithmException e) {
Log.e("no such an algorithm", e.toString());
} catch (Exception e) {
Log.e("exception", e.toString());
}
In facebook application's settings page inside Status & Review tab you should make app public. Or if you still don't want to make it public, you should add roles for all users that can use your android application (inside Roles tab).
Also, if it don't help, try to debug method
public void call(Session session, SessionState state, Exception exception)
There often normal messages why authorization wasn't successful
Upvotes: 6