Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Facebook friend picker SDK sample not working Android

Please help me to get the facebook friends from my profile using 3.14 SDK. There is no error in the code but the problem is getting empty list while fetching friends in my profile. I am getting the error in logcat saying
.

05-08 16:18:49.252: E/ActivityThread(25644): Failed to find provider info for com.facebook.orca.provider.PlatformProvider<br>
05-08 16:42:20.453: I/QCNEA(28696): |NIMS| getaddrinfo: hostname graph.facebook.com servname NULL numeric 4 appname <br>
05-08 16:51:32.482: D/Request(31861): Warning: Sessionless Request needs token but missing either application ID or client token<br>

Also i am producing the complete code for your reference below

FriendPickerApplication.java*

package com.facebook.samples.friendpicker;

import android.app.Application;
import com.facebook.model.GraphUser;

import java.util.List;

    // We use a custom Application class to store our minimal state data (which users have been selected).
    // A real-world application will likely require a more robust data model.
    public class FriendPickerApplication extends Application {
        private List<GraphUser> selectedUsers;

        public List<GraphUser> getSelectedUsers() {
            return selectedUsers;
        }

        public void setSelectedUsers(List<GraphUser> selectedUsers) {
            this.selectedUsers = selectedUsers;
        }
    }<br>

FriendPickerSampleActivity.java

package com.facebook.samples.friendpicker;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.facebook.AppEventsLogger;
import com.facebook.Session.NewPermissionsRequest;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.Session;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class FriendPickerSampleActivity extends FragmentActivity {
    private static final List<String> PERMISSIONS = new ArrayList<String>() {
        {
            add("user_friends");
            add("public_profile");
        }
    };
    private static final int PICK_FRIENDS_ACTIVITY = 1;
    private Button pickFriendsButton;
    private TextView resultsTextView;
    private UiLifecycleHelper lifecycleHelper;
    boolean pickFriendsWhenSessionOpened;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        resultsTextView = (TextView) findViewById(R.id.resultsTextView);
        pickFriendsButton = (Button) findViewById(R.id.pickFriendsButton);
        pickFriendsButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                onClickPickFriends();
            }
        });

        lifecycleHelper = new UiLifecycleHelper(this, new Session.StatusCallback() {
            @Override
            public void call(Session session, SessionState state, Exception exception) {
                onSessionStateChanged(session, state, exception);
            }
        });
        lifecycleHelper.onCreate(savedInstanceState);

        ensureOpenSession();
    }

    @Override
    protected void onStart() {
        super.onStart();

        // Update the display every time we are started.
        displaySelectedFriends(RESULT_OK);
    }

    @Override
    protected void onResume() {
        super.onResume();

        // Call the 'activateApp' method to log an app event for use in analytics and advertising reporting.  Do so in
        // the onResume methods of the primary Activities that an app may be launched into.
        AppEventsLogger.activateApp(this);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case PICK_FRIENDS_ACTIVITY:
                displaySelectedFriends(resultCode);
                break;
            default:
                Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
                break;
        }
    }

    private boolean ensureOpenSession() {
        if (Session.getActiveSession() == null ||
                !Session.getActiveSession().isOpened()) {
            Session.openActiveSession(
                    this, 
                    true, 
                    PERMISSIONS,
                    new Session.StatusCallback() {
                        @Override
                        public void call(Session session, SessionState state, Exception exception) {
                            onSessionStateChanged(session, state, exception);
                        }
                    });
            return false;
        }
        return true;
    }

    private boolean sessionHasNecessaryPerms(Session session) {
        if (session != null && session.getPermissions() != null) {
            for (String requestedPerm : PERMISSIONS) {
                if (!session.getPermissions().contains(requestedPerm)) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }

    private List<String> getMissingPermissions(Session session) {
        List<String> missingPerms = new ArrayList<String>(PERMISSIONS);
        if (session != null && session.getPermissions() != null) {
            for (String requestedPerm : PERMISSIONS) {
                if (session.getPermissions().contains(requestedPerm)) {
                    missingPerms.remove(requestedPerm);
                }
            }
        }
        return missingPerms;
    }

    private void onSessionStateChanged(final Session session, SessionState state, Exception exception) {
        if (state.isOpened() && !sessionHasNecessaryPerms(session)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage(R.string.need_perms_alert_text);
            builder.setPositiveButton(
                    R.string.need_perms_alert_button_ok, 
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            session.requestNewReadPermissions(
                                    new NewPermissionsRequest(
                                            FriendPickerSampleActivity.this, 
                                            getMissingPermissions(session)));
                        }
                    });
            builder.setNegativeButton(
                    R.string.need_perms_alert_button_quit,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    });
            builder.show();
        } else if (pickFriendsWhenSessionOpened && state.isOpened()) {
            pickFriendsWhenSessionOpened = false;

            startPickFriendsActivity();
        }
    }

    private void displaySelectedFriends(int resultCode) {
        String results = "";
        FriendPickerApplication application = (FriendPickerApplication) getApplication();

        Collection<GraphUser> selection = application.getSelectedUsers();
        if (selection != null && selection.size() > 0) {
            ArrayList<String> names = new ArrayList<String>();
            for (GraphUser user : selection) {
                names.add(user.getName());
            }
            results = TextUtils.join(", ", names);
        } else {
            results = "<No friends selected>";
        }

        resultsTextView.setText(results);
    }

    private void onClickPickFriends() {
        startPickFriendsActivity();
    }

    private void startPickFriendsActivity() {
        if (ensureOpenSession()) {
            Intent intent = new Intent(this, PickFriendsActivity.class);
            // Note: The following line is optional, as multi-select behavior is the default for
            // FriendPickerFragment. It is here to demonstrate how parameters could be passed to the
            // friend picker if single-select functionality was desired, or if a different user ID was
            // desired (for instance, to see friends of a friend).
            PickFriendsActivity.populateParameters(intent, null, true, true);
            startActivityForResult(intent, PICK_FRIENDS_ACTIVITY);
        } else {
            pickFriendsWhenSessionOpened = true;
        }
    }
} <br>

PickFriendsActivity.java

package com.facebook.samples.friendpicker;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.widget.Toast;
import com.facebook.FacebookException;
import com.facebook.model.GraphUser;
import com.facebook.widget.FriendPickerFragment;
import com.facebook.widget.PickerFragment;

import java.util.List;

public class PickFriendsActivity extends FragmentActivity {
    FriendPickerFragment friendPickerFragment;

    public static void populateParameters(Intent intent, String userId,
            boolean multiSelect, boolean showTitleBar) {
        intent.putExtra(FriendPickerFragment.USER_ID_BUNDLE_KEY, userId);
        intent.putExtra(FriendPickerFragment.MULTI_SELECT_BUNDLE_KEY,
                multiSelect);
        intent.putExtra(FriendPickerFragment.SHOW_TITLE_BAR_BUNDLE_KEY,
                showTitleBar);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pick_friends_activity);

        FragmentManager fm = getSupportFragmentManager();

        if (savedInstanceState == null) {
            // First time through, we create our fragment programmatically.
            final Bundle args = getIntent().getExtras();
            friendPickerFragment = new FriendPickerFragment(args);
            fm.beginTransaction()
                    .add(R.id.friend_picker_fragment, friendPickerFragment)
                    .commit();
        } else {
            // Subsequent times, our fragment is recreated by the framework and
            // already has saved and
            // restored its state, so we don't need to specify args again. (In
            // fact, this might be
            // incorrect if the fragment was modified programmatically since it
            // was created.)
            friendPickerFragment = (FriendPickerFragment) fm
                    .findFragmentById(R.id.friend_picker_fragment);
        }

        friendPickerFragment
                .setOnErrorListener(new PickerFragment.OnErrorListener() {
                    @Override
                    public void onError(PickerFragment<?> fragment,
                            FacebookException error) {
                        PickFriendsActivity.this.onError(error);
                    }
                });

        friendPickerFragment
                .setOnDoneButtonClickedListener(new PickerFragment.OnDoneButtonClickedListener() {
                    @Override
                    public void onDoneButtonClicked(PickerFragment<?> fragment) {
                        // We just store our selection in the Application for
                        // other activities to look at.
                        FriendPickerApplication application = (FriendPickerApplication) getApplication();
                        application.setSelectedUsers(friendPickerFragment
                                .getSelection());

                        setResult(RESULT_OK, null);
                        finish();
                    }
                });
    }

    private void onError(Exception error) {
        String text = getString(R.string.exception, error.getMessage());
        Toast toast = Toast.makeText(this, text, Toast.LENGTH_SHORT);
        toast.show();
    }

    @Override
    protected void onStart() {
        super.onStart();
        try {
            FriendPickerApplication application = (FriendPickerApplication) getApplication();
            List<GraphUser> selectedUsers = application.getSelectedUsers();
            if (selectedUsers != null && !selectedUsers.isEmpty()) {
                friendPickerFragment.setSelection(selectedUsers);
            }
            // Load data, unless a query has already taken place.
            friendPickerFragment.loadData(false);
        } catch (Exception ex) {
            onError(ex);
        }
    }
}<br>

Androidmanifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.facebook.samples.friendpicker"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:name=".FriendPickerApplication"
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.NoTitleBar" >
        <activity
            android:name="FriendPickerSampleActivity"
            android:label="@string/app_name"
            android:windowSoftInputMode="adjustResize" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="PickFriendsActivity"
            android:label="Pick Friends" >
        </activity>
        <activity
            android:name="com.facebook.LoginActivity"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />

        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/app_id" />

        <provider
            android:name="com.facebook.NativeAppCallContentProvider"
            android:authorities="com.facebook.app.NativeAppCallContentProvider1441068969495032"
            android:exported="true" />
    </application>

</manifest>
like image 439
Chandru Avatar asked Dec 05 '22 06:12

Chandru


1 Answers

After a long struggle I found my own solution to the above question. Facebook have released their new SDK recently to enhance the level of security. There are a few requirements to use facebook SDK in your app.

  1. The app should be sent for submission and needs to be approved by facebook to be use inside facebook, to enable your own app to show friends details, access locations and other special permissions The approval formalities are similar to the ones for app store in Google Play.

  2. The application must be listed in Google Play, or you may be able to integrate it as a test user (i.e like beta testing in Google Play).

  3. The application should have a proper package name, launching activity, domain name, website url and email.

  4. The app id registered must match with an app name and hash key that must be generated for a user developing on different machines

  5. The basic application information, including screenshots, description, and app logo needs to be added

  6. Once after the successful approval, an "active" symbol will be displayed near your app name.

I hope this will be useful for others!!!

More information on Facebook site.

like image 62
Chandru Avatar answered Dec 10 '22 11:12

Chandru