Error when trying to trigger Facebook Share in android SDK

0

I'm developing an android application where the person can log in via Facebook.

I'm trying to develop the "share" option so that an application message can be posted on the user's timeline, but I'm encountering the following error:

Session: an attempt was made to request new permissions for a session that has a pending request

I believe the error is at the moment when I try to request permission to publish to the user. Here is the code below, where authentication and the facebook share process are done:

Main activity

public class MainActivity extends FragmentActivity {

    private MainFragment mainFragment;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (savedInstanceState == null) {
            // Add the fragment on initial activity setup
            mainFragment = new MainFragment();
            getSupportFragmentManager()
            .beginTransaction()
            .add(android.R.id.content, mainFragment)
            .commit();
        } else {
            // Or set the fragment from restored state info
            mainFragment = (MainFragment) getSupportFragmentManager()
            .findFragmentById(android.R.id.content);
        }
    }
}

Fragment:

public class MainFragment extends Fragment{

    private static final String TAG = "MainFragment";
    private UiLifecycleHelper uiHelper;

    private Button shareButton;

    private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
    private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
    private boolean pendingPublishReauthorization = false;

    @Override
    public View onCreateView(LayoutInflater inflater, 
            ViewGroup container, 
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_main, container, false);
        shareButton = (Button) view.findViewById(R.id.shareButton);
        LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
        authButton.setFragment(this);
        authButton.setReadPermissions(Arrays.asList("user_likes", "user_status"));
        if (savedInstanceState != null) {
            pendingPublishReauthorization = 
                savedInstanceState.getBoolean(PENDING_PUBLISH_KEY, false);
        }

        shareButton = (Button) view.findViewById(R.id.shareButton);
        shareButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                publishStory();        
            }
        });

        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Session.getActiveSession().onActivityResult(getActivity(), requestCode, resultCode, data);
        uiHelper.onActivityResult(requestCode, resultCode, data);
    }

    private void onSessionStateChange(Session session, SessionState state, Exception exception) {
        if (state.isOpened()) {
            shareButton.setVisibility(View.VISIBLE);
            if (pendingPublishReauthorization && 
                    state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
                pendingPublishReauthorization = false;
                publishStory();
            }
        } else if (state.isClosed()) {
            shareButton.setVisibility(View.INVISIBLE);
        }
    }

    private Session.StatusCallback callback = new Session.StatusCallback() {
        @Override
        public void call(Session session, SessionState state, Exception exception) {
            onSessionStateChange(session, state, exception);
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        uiHelper = new UiLifecycleHelper(getActivity(), callback);
        uiHelper.onCreate(savedInstanceState);

    }

    @Override
    public void onResume() {
        super.onResume();
        // For scenarios where the main activity is launched and user
        // session is not null, the session state change notification
        // may not be triggered. Trigger it if it's open/closed.
        Session session = Session.getActiveSession();
        if (session != null &&
               (session.isOpened() || session.isClosed()) ) {
            onSessionStateChange(session, session.getState(), null);
        }

        uiHelper.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        uiHelper.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        uiHelper.onDestroy();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(PENDING_PUBLISH_KEY, pendingPublishReauthorization);
        uiHelper.onSaveInstanceState(outState);
    }

    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", "Facebook SDK for Android");
            postParams.putString("caption", "Build great social apps and get more installs.");
            postParams.putString("description", "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");

            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(getActivity()
                             .getApplicationContext(),
                             error.getErrorMessage(),
                             Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getActivity()
                                 .getApplicationContext(), 
                                 postId,
                                 Toast.LENGTH_LONG).show();
                    }
                }
            };

            Request request = new Request(session, "me/feed", postParams, 
                                  HttpMethod.POST, callback);

            RequestAsyncTask task = new RequestAsyncTask(request);
            task.execute();
        }

    }

    private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
        for (String string : subset) {
            if (!superset.contains(string)) {
                return false;
            }
        }
        return true;
    }
}

Activity XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <com.facebook.widget.LoginButton
        android:id="@+id/authButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="30dp" />

    <Button
        android:id="@+id/shareButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:gravity="center"
        android:text="Share"
        android:textStyle="bold"
        android:visibility="invisible" />

</LinearLayout>

LogCat returns:

07-08 16:07:49.916: E/AndroidRuntime(710): FATAL EXCEPTION: main
07-08 16:07:49.916: E/AndroidRuntime(710): java.lang.UnsupportedOperationException: Session: an attempt was made to request new permissions for a session that has a pending request.
07-08 16:07:49.916: E/AndroidRuntime(710):  at com.facebook.Session.requestNewPermissions(Session.java:1245)
07-08 16:07:49.916: E/AndroidRuntime(710):  at com.facebook.Session.requestNewPublishPermissions(Session.java:592)
07-08 16:07:49.916: E/AndroidRuntime(710):  at com.example.facebooksharedemo.MainFragment.publishStory(MainFragment.java:146)
07-08 16:07:49.916: E/AndroidRuntime(710):  at com.example.facebooksharedemo.MainFragment.onSessionStateChange(MainFragment.java:79)
07-08 16:07:49.916: E/AndroidRuntime(710):  at com.example.facebooksharedemo.MainFragment.access$0(MainFragment.java:73)
07-08 16:07:49.916: E/AndroidRuntime(710):  at com.example.facebooksharedemo.MainFragment$1.call(MainFragment.java:89)
07-08 16:07:49.916: E/AndroidRuntime(710):  at com.facebook.Session$4$1.run(Session.java:1542)
07-08 16:07:49.916: E/AndroidRuntime(710):  at android.os.Handler.handleCallback(Handler.java:605)
07-08 16:07:49.916: E/AndroidRuntime(710):  at android.os.Handler.dispatchMessage(Handler.java:92)
07-08 16:07:49.916: E/AndroidRuntime(710):  at android.os.Looper.loop(Looper.java:137)
07-08 16:07:49.916: E/AndroidRuntime(710):  at android.app.ActivityThread.main(ActivityThread.java:4424)
07-08 16:07:49.916: E/AndroidRuntime(710):  at java.lang.reflect.Method.invokeNative(Native Method)
07-08 16:07:49.916: E/AndroidRuntime(710):  at java.lang.reflect.Method.invoke(Method.java:511)
07-08 16:07:49.916: E/AndroidRuntime(710):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
07-08 16:07:49.916: E/AndroidRuntime(710):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
07-08 16:07:49.916: E/AndroidRuntime(710):  at dalvik.system.NativeStart.main(Native Method)

Login is successful, but when I click on share, the application does not request the new permissions, just saying that I already authorized the app, and it gives the error.

From what I understood. It is not adding the publishing permission and is making the same request again, resulting in the error.

Can anyone help?

    
asked by anonymous 07.07.2014 / 19:06

0 answers