Android上的应用重启后,我在Facebook上的当前访问令牌丢失(ListFragment)

时间:2015-08-01 19:11:14

标签: android facebook facebook-graph-api parse-platform facebook-sdk-4.0

我不知道我的代码中是否遗漏了某些内容,但我有一个viewpager有4个标签。其中一个是寻找FaceBook的朋友。您可以使用FaceBook登录应用程序,但是当您在此选项卡中时,如果您没有使用FaceBook登录,它将显示一个登录按钮以获取正在玩游戏的任何朋友。在用户点击按钮并登录成功后,一切看起来都很好,这个人可以看到他们所有的朋友。但是,如果此人杀死应用程序然后重新打开应用程序,它将再次显示该按钮而不是已登录的人。如果currentaccesstoken为空,则显示该按钮,并且由于此人已登录,因此不应为null。请帮忙。

这是我的代码:

public class FacebookFriends extends ListFragment
        implements ListAdapterAddFriends.customButtonListener {
    //variable declaration/initialization
    public static final String TAG = FacebookFriends.class.getSimpleName(); //tag with class name
    protected ParseObject mFriendsRelation;     //parse object for friend relation table
    protected List<ParseUser> mUsers;           //list of ParseUsers
    protected ParseUser mCurrentUser;           //ParseUser to get the current user
    private ListView listView;                  //Listview for facebook friends
    private TextView empty;
    ListAdapterAddFriends adapter;              //adapter from the listAdapterAddFriends Class
    Toolbar mToolbar;                           //Custom Toolbar
    ProgressBar progressBar;                    //Progress bar to indicate when loading
    String[] friendId;                          //getting friendID from Facebook
    String[] friendName;                        //getting friendName from Facebook
    // Creating Facebook CallbackManager Value
    public static CallbackManager callbackmanager;
    View mRootView;
    Button facebookLoginButton;


    /**
     * Method that start this class
     *
     * @param savedInstanceState this will save an instance of the class when resume
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mRootView = inflater.inflate(R.layout.tab_facebook_friends, container, false);
        setHasOptionsMenu(true);

        //initializing facebook button
        facebookLoginButton = (Button) mRootView.findViewById(R.id.facebook_login);

        facebookLoginButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                facebookLogin();
            }
        });

        //initializing empty text
        empty = (TextView) mRootView.findViewById(android.R.id.empty);

        //initializing listview
        listView = (ListView) mRootView.findViewById(android.R.id.list);
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);



        return mRootView;
    }

    /**
     * this method is call when the app in resume
     */
    @Override
    public void onResume() {
        super.onResume();

        mCurrentUser = ParseUser.getCurrentUser();    //getting current user

        if (AccessToken.getCurrentAccessToken() == null) {
            facebookLoginButton.setVisibility(View.VISIBLE);
            empty.setVisibility(View.INVISIBLE);
        } else {
            getFacebookFriends();                         //calling method to look for facebook friends
        }
    }

    /**
     * method that look for facebook friends with facebook api
     */
    private void getFacebookFriends() {
        mCurrentUser = ParseUser.getCurrentUser();

        /* make the API call */
        new GraphRequest(
                AccessToken.getCurrentAccessToken(),
                "/me/friends",
                null,
                HttpMethod.GET,
                new GraphRequest.Callback() {
                    public void onCompleted(GraphResponse response) {
                        /* handle the result */
                        JSONObject jsonObject = response.getJSONObject();
                        try {
                            JSONArray data = jsonObject.getJSONArray("data");

                            friendId = new String[data.length()];
                            friendName = new String[data.length()];

                            for (int i = 0; i < data.length(); i++) {
                                JSONObject jsonFriends = data.getJSONObject(i);

                                friendId[i] = jsonFriends.getString("id");
                                friendName[i] = jsonFriends.getString("name");
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                        ParseQuery<ParseUser> query = ParseUser.getQuery();
                        if (friendId.length > 1) {
                            query.whereContainedIn("facebookID", Arrays.asList(friendId));
                        } else {
                            query.whereEqualTo("facebookID", friendId[0]);
                        }


                        query.findInBackground(new FindCallback<ParseUser>() {
                            public void done(List<ParseUser> usr, ParseException e) {
                                //getActivity().setProgressBarIndeterminateVisibility(false);
                                if (e == null) {
                                    // The query was successful.
                                    mUsers = usr;
                                    addFriendCheckMarks(mUsers);

                                    adapter = new ListAdapterAddFriends(getListView().getContext(),
                                            mUsers);
                                    adapter.setCustomButtonListener(FacebookFriends.this);
                                    listView.setAdapter(adapter);

                                } else {
                                    // Something went wrong.
                                    Log.e("ERROR", e.getMessage());
                                    AlertDialog.Builder builder =
                                            new AlertDialog.Builder(getActivity());
                                    builder.setMessage(e.getMessage())
                                            .setTitle("Oops we are sorry")
                                            .setPositiveButton(android.R.string.ok, null);
                                    AlertDialog dialog = builder.create();
                                    dialog.show();
                                }
                            }
                        });
                    }
                }
        ).executeAsync();


    }


    private void facebookLogin() {
        callbackmanager = CallbackManager.Factory.create();

        // Set permissions
        LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "user_friends"));

        LoginManager.getInstance().registerCallback(callbackmanager,
                new FacebookCallback<LoginResult>() {
                    @Override
                    public void onSuccess(LoginResult loginResult) {

                        GraphRequest.newMeRequest(
                                loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
                                    @Override
                                    public void onCompleted(JSONObject json, GraphResponse response) {
                                        if (response.getError() != null) {
                                            // handle error
                                            System.out.println("ERROR");
                                        } else {
                                            System.out.println("Success");
                                            try {

                                                ParseUser parseUser = ParseUser.getCurrentUser();
                                                if (json != null && parseUser != null


                                                && json.optString("name").length() > 0) {
                                                parseUser.put("facebookID", json.getString("id"));
                                                parseUser.saveInBackground(new SaveCallback() {
                                                    @Override
                                                    public void done(ParseException e) {
                                                        if (e == null) {


                                                        }
                                                    }
                                                });
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }

                            }).executeAsync();
                }

                @Override
                public void onCancel() {
                    Log.d("CANCEL", "On cancel");
                }

                @Override
                public void onError(FacebookException error) {
                    Log.d("ERROR", error.toString());
                }
            });
}

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

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

}

我错过了什么吗?我正在应用程序类中初始化我的sdk,如此

//initializing parsefacebookutil to signup/signin with facebook
        ParseFacebookUtils.initialize(this);

0 个答案:

没有答案