Why can't I use my ArrayList variable outside FacebookCallback

陌路散爱 提交于 2020-01-06 02:19:26

问题


Hi I am trying to implement Facebook login and getting friends list. I am storing my Friends'name and profile picture url into ArrayList<TaggedFriends> Where TaggedFriends class will have set and get methods.

I am now working in Fragment class named MainFragment. Here, I am storing values into taggableFriends variable inside a FacebookCallback Session. But I can't access it to any other places I am trying to store it into SharedPreferences but when I try to store, it returning null value.

Here is my full code of MainFragment

public class MainFragment extends Fragment {
    String email, tag = "MainFragment kbt";
    ArrayList<TaggableFriends> taggableFriends = new ArrayList<TaggableFriends>();
    ArrayList<TaggableFriends> testing = new ArrayList<>();
    MainActivity mainActivity ;

    private CallbackManager callbackManager;
    private TextView textView;

    private AccessTokenTracker accessTokenTracker;
    private ProfileTracker profileTracker;


    private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            AccessToken accessToken = loginResult.getAccessToken();
            Profile profile = Profile.getCurrentProfile();        
            new GraphRequest(
                    AccessToken.getCurrentAccessToken(),
                    "/me/taggable_friends",
                    null,
                    HttpMethod.GET,
                    new GraphRequest.Callback() {
                        public void onCompleted(GraphResponse response) {
                            //    handle the result
                            Log.d("RESPONSE KBT", response.getRawResponse());
                            try {

                                JSONObject obj = new JSONObject(response.getRawResponse());
                                JSONArray array = obj.getJSONArray("data");
                                for (int i = 0; i < array.length(); i++) {
                                    JSONObject indi = array.getJSONObject(i);
                                    JSONObject pic = indi.getJSONObject("picture");
                                    JSONObject data = pic.getJSONObject("data");
                                    String name = indi.getString("name");
                                    String url = data.getString("url");
                                    TaggableFriends tf = new TaggableFriends(name, url);
                                    taggableFriends.add(tf);
                                    Log.d("NAME", tf.getName());
                                    Log.d("SIZE", ":"+taggableFriends.size());


                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            Log.d(tag,"SECOND SIZE"+taggableFriends.size());
                           //
                        }
                    }
            ).executeAsync();           

            JSONArray mJSONArray = new JSONArray(taggableFriends);
            SharedPreferences mPrefs = getActivity().getSharedPreferences("My_File",Context.MODE_PRIVATE);
            SharedPreferences.Editor mEditor = mPrefs.edit();
            mEditor.putString("myKey", mJSONArray.toString());
            Log.d(tag,"STRING JSON : "+mJSONArray.toString());
            mEditor.commit();
        displayMessage(profile);
        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onError(FacebookException e) {

        }
    };


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

        FacebookSdk.sdkInitialize(getActivity().getApplicationContext());

        callbackManager = CallbackManager.Factory.create();

        accessTokenTracker = new AccessTokenTracker() {
            @Override
            protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {

            }
        };

        profileTracker = new ProfileTracker() {
            @Override
            protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
                displayMessage(newProfile);
            }
        };

        accessTokenTracker.startTracking();
        profileTracker.startTracking();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_main, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
        textView = (TextView) view.findViewById(R.id.textView);

        // loginButton.setReadPermissions("user_friends");
        loginButton.setReadPermissions(Arrays.asList("email", "user_friends", "read_custom_friendlists"));
        // loginButton.setReadPermissions(Arrays.asList("public_profile", "user_friends"));
        loginButton.setFragment(this);
        loginButton.registerCallback(callbackManager, callback);
        Log.d(tag,"taggable "+taggableFriends.size());
      //  if(taggableFriends.size()!=0)


    }

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

    }

    private void displayMessage(Profile profile) {
        if (profile != null) {
            textView.setText(profile.getName());

        }
    }
}

Please notice inside FacebookCallBack --> onSuccess() method. There I am storing my values for variable taggedFriends

Immediately after that I am storing taggedFriends into SharedPreferences. But at that place, taggedFriends variable was null. It doesn't contain anything. I checked with Logcat.

Inside onSuccess() method its values are there, when I use out of that method, it's null. What is the problem?


回答1:


The Graph API call is executed asynchronously, i.e. in a separate thread. Looks like when you try and store the values in SharedPreferences, the async call hasn't completed yet and you get null. Try moving the storing in SharedPreferences part inside the onCompleted method, right after you add it to your ArrayList.



来源:https://stackoverflow.com/questions/34132418/why-cant-i-use-my-arraylist-variable-outside-facebookcallback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!