Facebook图表api android [英] Facebook graph api android

查看:150
本文介绍了Facebook图表api android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to fetch the user data using graph api but unable to do so. I know there are many answers available to this question but didn't get the one that will help me.

我使用的是facebook sdk v3.20.对于认证部分我正在使用亚马逊认知服务。这是我的MainActivity代码: -

I am using facebook sdk v3.20.For authentication part I am using amazon cognito service. Here's my MainActivity code:-

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

And this is my facebookinfo code for calling graph api:-

public class FacebookInfo extends Activity {

public class FacebookInfo extends 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活动,并且当我运行我的应用程序崩溃后,就以这种方式集成。

I want to integrate these two codes. I have tried making two different activities of these codes and calling the facebookinfo activity from MainActivity and after integrating in that way whenever I run my app it crashes.

所以请有人帮我这个吗如何整合这两个代码以获取用户的详细信息?

So please can someone help me with this??? How to integrate these two codes to get the user details????

推荐答案

以下是完整的代码以获取Facebook个人资料...
我已经使用Facebook SDK 4.4.0

Here is the complete code to get Facebook profile details... I have used 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中

Create the facebook appid and place it in strings.xml

这篇关于Facebook图表api android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆