繁体   English   中英

Facebook图形API Android

[英]Facebook graph api android

我正在尝试使用图形API获取用户数据,但无法这样做。 我知道这个问题有很多答案,但是没有一个可以帮助我的答案。

我正在使用Facebook SDK v3.20。对于身份验证部分,我正在使用Amazon Cognito服务。 这是我的MainActivity代码:

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);
}

这是我的用于调用图形API的facebookinfo代码:-

公共类FacebookInfo扩展了活动{

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活动,以这种方式集成后,无论何时运行我的应用程序,它都会崩溃。

所以有人可以帮我吗??? 如何集成这两个代码以获得用户详细信息?

这是获取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中

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM