Facebook 图 api android

Facebook graph api android

我正在尝试使用图表 api 获取用户数据,但无法这样做。我知道这个问题有很多答案,但没有找到对我有帮助的答案。

我正在使用 facebook sdk v3。20.For 身份验证部分我正在使用 amazon cognito 服务。这是我的主要 Activity 代码:-

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main_activity);

    /**
     * Initializes the sync client. This must be call before you can use it.
     */
    CognitoSyncClientManager.init(this);
    btnLoginFacebook = (Button) findViewById(R.id.btnLoginFacebook);
    btnLoginFacebook.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // start Facebook Login
            Session.openActiveSession(MainActivity.this, true,
                    MainActivity.this);
        }
    });
    btnLoginFacebook.setEnabled(getString(R.string.facebook_app_id) != "facebook_app_id");


    final Session session = Session
            .openActiveSessionFromCache(MainActivity.this);
    if (session != null) {
        setFacebookSession(session);
    }

    Button btnWipedata = (Button) findViewById(R.id.btnWipedata);
    btnWipedata.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            new AlertDialog.Builder(MainActivity.this)
                    .setTitle("Wipe data?")
                    .setMessage(
                            "This will log off your current session and wipe all user data. "
                                    + "Any data not synchronized will be lost.")
                    .setPositiveButton("Yes",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                        int which) {
                                    // clear login status
                                    if (session != null) {
                                        session.closeAndClearTokenInformation();
                                    }
                                    btnLoginFacebook
                                            .setVisibility(View.VISIBLE);
                                    if (mAuthManager != null) {
                                        mAuthManager
                                                .clearAuthorizationState(null);
                                    }

                                    CognitoSyncClientManager.getInstance()
                                            .wipeData();

                                    // Wipe shared preferences
                                    AmazonSharedPreferencesWrapper.wipe(PreferenceManager
                                            .getDefaultSharedPreferences(MainActivity.this));
                                }

                            })
                    .setNegativeButton("No",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                        int which) {
                                    dialog.cancel();
                                }
                            }).show();
        }
    });

    startActivity(new Intent(MainActivity.this, FacebookInfo.class));

}

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

这是我调用图表的 facebookinfo 代码 api:-

public class FacebookInfo 扩展 Activity {

private static final String TAG = "MainActivity";
String get_id, get_name, get_gender, get_email, get_birthday;

private Session.StatusCallback fbStatusCallback = new Session.StatusCallback() {
    public void call(Session session, SessionState state, Exception exception) {
        if (state.isOpened()) {
            Request.newMeRequest(session, new Request.GraphUserCallback() {
                public void onCompleted(GraphUser user, Response response) {
                    if (response != null) {
                        // do something with <response> now
                        try {
                            get_id = user.getId();
                            get_name = user.getName();
                            get_gender = (String) user.getProperty("gender");
                            get_email = (String) user.getProperty("email");
                            get_birthday = user.getBirthday();

                            Log.d(TAG, user.getId() + "; " +
                                    user.getName() + "; " +
                                    (String) user.getProperty("gender") + "; " +
                                    (String) user.getProperty("email") + "; " +
                                    user.getBirthday() + "; " +
                                    (String) user.getProperty("locale") + "; " +
                                    user.getLocation());
                        } catch (Exception e) {
                            e.printStackTrace();
                            Log.d(TAG, "Exception e");
                        }

                    }
                }
            });
        }
    }
};

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fbinfo);
    try {
        openActiveSession(this, true, fbStatusCallback, Arrays.asList(
                new String[]{"email", "user_location", "user_birthday",
                        "user_likes", "publish_actions"}), savedInstanceState);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private Session openActiveSession(Activity activity, boolean allowLoginUI,
                                  Session.StatusCallback callback, List<String> permissions, Bundle savedInstanceState) {
    Session.OpenRequest openRequest = new Session.OpenRequest(activity).
            setPermissions(permissions).setLoginBehavior(SessionLoginBehavior.
            SSO_WITH_FALLBACK).setCallback(callback).
            setDefaultAudience(SessionDefaultAudience.FRIENDS);

    Session session = Session.getActiveSession();
    Log.d(TAG, "" + session);
    if (session == null) {
        Log.d(TAG, "" + savedInstanceState);
        if (savedInstanceState != null) {
            session = Session.restoreSession(this, null, fbStatusCallback, savedInstanceState);
        }
        if (session == null) {
            session = new Session(this);
        }
        Session.setActiveSession(session);
        if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED) || allowLoginUI) {
            session.openForRead(openRequest);
            return session;
        }
    }
    return null;
}


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

}

我想整合这两个代码。我已经尝试对这些代码进行两种不同的活动,并从 MainActivity 调用 facebookinfo activity,并且在以这种方式集成之后,每当我 运行 我的应用程序崩溃时。

所以有人可以帮我解决这个问题吗???如何整合这两个代码获取用户详情????

这是获取 Facebook 个人资料详细信息的完整代码... 我用过 Facebook SDK 4.4.0

public class MainActivity extends Activity {

    LoginButton loginButton;
    private CallbackManager callbackManager;
    private ProgressDialog pDialog;
    URL myurl;
    String profilepic;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(MainActivity.this);
        setContentView(R.layout.activity_main);

        loginButton = (LoginButton) findViewById(R.id.login_button);
        loginButton.setReadPermissions(Arrays
                .asList("public_profile, email, user_birthday, user_friends"));

        callbackManager = CallbackManager.Factory.create();
        loginButton.registerCallback(callbackManager,
                new FacebookCallback<LoginResult>() {
                    @Override
                    public void onSuccess(LoginResult loginResult) {
                        new fblogin().execute(loginResult.getAccessToken());
                    }

                    @Override
                    public void onCancel() {

                    }

                    @Override
                    public void onError(FacebookException e) {

                    }
                });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public class fblogin extends AsyncTask<AccessToken, String, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Loading...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        protected String doInBackground(AccessToken... params) {
            GraphRequest request = GraphRequest.newMeRequest(params[0],
                    new GraphRequest.GraphJSONObjectCallback() {
                        @Override
                        public void onCompleted(JSONObject object,
                                GraphResponse response) {
                            Log.v("MainActivity", response.toString());
                            try {
                                String profile_pic = object.getString("id");
                                try {
                                    myurl = new URL(
                                            "https://graph.facebook.com/"
                                                    + profile_pic + "/picture");
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                profilepic = myurl.toString();


                                Log.v("Name", object.getString("first_name"));
                                Log.v("Email", object.getString("email"));
                                Log.v("Profile Pic Url", profilepic);
                                Log.v("Gender", object.getString("gender"));

                            } catch (JSONException jse) {
                                // session.logoutUser();
                                Log.e("fb json exception", jse.toString());
                            }
                        }
                    });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "id,first_name,email,gender");
            request.setParameters(parameters);
            GraphRequest.executeBatchAndWait(request);
            return null;
        }

        protected void onPostExecute(String file_url) {
            pDialog.dismiss();

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int responseCode,
            Intent intent) {
        // TODO Auto-generated method stub
        callbackManager.onActivityResult(requestCode, responseCode, intent);
    }
}

在清单文件中添加这个

  <activity
            android:name="com.facebook.FacebookActivity"
            android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />

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

创建 facebook appid 并将其放在 strings.xml