用户通过我的Android应用程序登录后获取用户的Facebook数据的问题

时间:2014-11-18 05:52:48

标签: android facebook facebook-graph-api graph

debug中的问题截图:

Screen shot of the problem

以下是我的facebook登录文件的完整代码

import java.util.ArrayList;
import java.util.Arrays;

import org.json.JSONArray;
import org.json.JSONObject;

import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.RequestAsyncTask;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

public class MainFragment extends Fragment {
    private static final String TAG = "MainFragment";
    private UiLifecycleHelper uiHelper;
    Context context;


    private void onSessionStateChange(Session session, SessionState state,
            Exception exception) {
        if (state.isOpened()) {
               Request.newMeRequest(session, new Request.GraphUserCallback() {

                      // callback after Graph API response with user object
                  @Override
                  public void onCompleted(GraphUser user, Response response) {

              if (user != null) {
                        // Display the parsed user info
                      //  userInfoTextView.setText(buildUserInfoDisplay(user));
            //            Log.d(TAG,"Failed to login");
                    }
                  }
                }).executeAsync();

        }

        else if (state.isClosed()) {
            Log.i(TAG, "Logged out...");
        }
    }

    private Session.StatusCallback callback = new Session.StatusCallback() {
        @Override
        public void call(Session session, SessionState state,
                Exception exception) {
            onSessionStateChange(session, state, exception);
        }
    };

    private String buildUserInfoDisplay(GraphUser user) {
        StringBuilder userInfo = new StringBuilder("");

        // Example: typed access (name)
        // - no special permissions required
        userInfo.append(String.format("Name: %s\n\n", user.getName()));

        // Example: typed access (birthday)
        // - requires user_birthday permission
        userInfo.append(String.format("Birthday: %s\n\n", user.getBirthday()));

        // Example: partially typed access, to location field,
        // name key (location)
        // - requires user_location permission
        userInfo.append(String.format("Location: %s\n\n", user.getLocation()
                .getProperty("name")));

        // Example: access via property name (locale)
        // - no special permissions required
        userInfo.append(String.format("Locale: %s\n\n",
                user.getProperty("locale")));

        // Example: access via key for array (languages)
        // - requires user_likes permission
        JSONArray languages = (JSONArray) user.getProperty("languages");
        if (languages.length() > 0) {
            ArrayList<String> languageNames = new ArrayList<String>();
            for (int i = 0; i < languages.length(); i++) {
                JSONObject language = languages.optJSONObject(i);
                // Add the language name to a list. Use JSON
                // methods to get access to the name field.
                languageNames.add(language.optString("name"));
            }
            userInfo.append(String.format("Languages: %s\n\n",
                    languageNames.toString()));
        }

        return userInfo.toString();
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.login_layout, container, false);
        LoginButton authButton = (LoginButton) view
                .findViewById(R.id.authButton);
        authButton.setFragment(this);
        authButton.setReadPermissions(Arrays.asList("user_about_me",
                "user_likes", "user_status", "user_groups"));

        return view;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getActivity();
        uiHelper = new UiLifecycleHelper(getActivity(), callback);
        uiHelper.onCreate(savedInstanceState);
    }

    public void onResume() {
        super.onResume();
        uiHelper.onResume();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        uiHelper.onActivityResult(requestCode, resultCode, data);

    }

    @Override
    public void onPause() {
        super.onPause();
        uiHelper.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        uiHelper.onDestroy();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        uiHelper.onSaveInstanceState(outState);
    }
}

对此问题的任何帮助都将是一个很大的帮助,谢谢......

1 个答案:

答案 0 :(得分:0)

尝试使用以下代码,它可能有所帮助,在我的情况下正常工作。

import java.util.Arrays;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
public class MainFragment extends Fragment {

    private UiLifecycleHelper uiHelper;

    private Session.StatusCallback callback = new Session.StatusCallback() {
        @Override
        public void call(final Session session, final SessionState state, final Exception exception) {
            onSessionStateChange(session, state, exception);
        }
    };


    private TextView userInfoTextView;
    private String fbAccessToken;
    private ImageView userProfileImg;


    @Override
    public View onCreateView(LayoutInflater inflater,
            ViewGroup container,
            Bundle savedInstanceState) {


        View view = inflater.inflate(R.layout.activity_main, container, false);

        LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);

        authButton.setFragment(this);

        authButton.setReadPermissions(Arrays.asList("user_location", "user_birthday", "user_likes"));

        userInfoTextView = (TextView) view.findViewById(R.id.userInfoTextView);

        userProfileImg = (ImageView)view.findViewById(R.id.user_profile_img);

        return view;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        uiHelper = new UiLifecycleHelper(getActivity(), callback);

        uiHelper.onCreate(savedInstanceState);
    }

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

        Session session = Session.getActiveSession();
        if (session != null &&
                (session.isOpened() || session.isClosed()) ) {

            onSessionStateChange(session, session.getState(), null);
        }

        uiHelper.onResume();

    }


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

        uiHelper.onActivityResult(requestCode, resultCode, data);
    }


    @Override
    public void onPause() {
        super.onPause();

        uiHelper.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();


        uiHelper.onDestroy();


    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        uiHelper.onSaveInstanceState(outState);
    }

    @SuppressWarnings("deprecation")
    private void onSessionStateChange(final Session session, SessionState state, Exception exception) {


        if (state.isOpened()) {

            userInfoTextView.setVisibility(View.VISIBLE);


            // Request user data and show the results
            Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
                @Override
                public void onCompleted(GraphUser user, Response response) {

                    if (user != null) {

                        userInfoTextView.setText(buildUserInfoDisplay(user,fbAccessToken));
                    }
                }

            });
        } 

        else if (state.isClosed()) {
            Toast.makeText(getActivity(), "Please Login", Toast.LENGTH_SHORT).show();
            userInfoTextView.setVisibility(View.GONE);
        }
    }
    private String buildUserInfoDisplay(GraphUser user,String token) {



        StringBuilder userInfo = new StringBuilder("");

        userInfo.append(String.format("Name: %s\n\n",
                user.getName()));


        userInfo.append(String.format("Birthday: %s\n\n",
                user.getBirthday()));


        userInfo.append(String.format("Id: %s\n\n",
                user.getId()));


        userInfo.append(String.format("Locale: %s\n\n",
                user.getProperty("locale")));

        userInfo.append(String.format("Link: %s\n\n",
                user.getLink()));


        userInfo.append(String.format("Gender:%s\n\n",user.asMap().get("gender").toString()));

        userInfo.append(String.format("Token:%s\n\n",token));

        return userInfo.toString();

    }

}