Facebook amigo picker amostra SDK não funciona Android

? Chandru @ | Original: StackOverFlow
---

Por favor, me ajude a obter os amigos do facebook do meu perfil usando 3,14 SDK. Não há erro no código, mas o problema está ficando lista vazia ao buscar amigos no meu perfil. Estou recebendo o erro no logcat ditado .

* 08/05 16: 18: 49,252 : E / ActivityThread ( 25644 ): Não foi possível encontrar informações provedor para com.facebook.orca.provider.PlatformProvider 08/05 16: 42: 20,453 : I / QCNEA ( 28696 ): | NIMS | getaddrinfo : hostname graph.facebook.com servname NULL numérica de 4 appname 08/05 16: 51: 32,482 : D / Request ( 31861 ): Atenção : sessionless Request precisa meramente simbólica, mas faltando ou ID aplicação ou token de cliente.

Também eu estou produzindo o código completo para sua referência abaixo

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>
---

Top 5 Responder

1Chandru @

Depois de uma longa luta que eu encontrei minha própria solução para a questão acima. Facebook lançou seu novo SDK recentemente para aumentar o nível de fins de segurança . A seguir estão os poucos exigência de utilização de facebook SDK em seu app .

O aplicativo deve enviar para a apresentação e precisa obter a aprovação da equipe do Facebook para usar integração facebook em seu próprio aplicativo para listar amigos detalhes, acessar locais e para aceder a outras permissões especiais As formalidades de aprovação são similares como loja listagem app no Google Play .

O pedido deve ser listado no Google Play ou você poderia capaz de integrá-lo como um usuário de teste (ou seja, como o teste beta no google play).

A aplicação deve ter um nome de pacote adequado, a atividade de lançamento, nome de domínio, URL do site e e-mail.

O id app registrado deve corresponder com um nome de aplicativo e chave de hash deve ser gerado para um usuário a desenvolver com máquinas diferentes

Os screenshots de exemplo da aplicação, descrição e logotipo app precisa ser adicionado

Uma vez que, após a aprovação de sucesso da equipe ele vai mostrar um símbolo ativo perto do seu nome do aplicativo.

Espero que seja útil para outras pessoas !!!

https://developers.facebook.com/docs/apps/review .

2Jonas @

Depois de passar um bom número de horas tentando resolver isso, eu gostaria de acrescentar o seguinte para quem ainda está procurando :

The only friends you will see in the list with user_friend permissions is other users that have logged in and approved your app. I.e. if no-one else is using it, you will se noone in the list (I know, if you read it all, this is obvious) The easiest way of testing this is to set up a test app, add test users in the dev interface for facebook under "Roles", make sure that the test users are friends and then log in with each use on your app. Only then will they show up in the list.

A menos que você pedir especificamente, o seu aplicativo não terá a permissão user_friends ( você não faz, no entanto, precisam rever isso com Facebook, uma vez que faz parte das permissões básicas ) - I adicionou ao onCreateView no Segmento Splash ( a partir de o Scrumptios / sample Entrar no SDK) como este:

LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("user_friends"));

Use a interface de usuário de teste Facebook para efetuar o login no Facebook como seu usuário teste para validar que eles foram aceitando as permissões corretas ( sob apps) .