com.facebook.FacebookException: Attempted to use a Session that was not open
android, facebook
Solution
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
Problem
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(); } ```