为什么我不能在 FacebookCallback 之外使用我的 ArrayList 变量 [英] Why can't I use my ArrayList variable outside FacebookCallback

查看:20
本文介绍了为什么我不能在 FacebookCallback 之外使用我的 ArrayList 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现 Facebook 登录和获取好友列表.我将我的好友姓名和个人资料图片 url 存储到 ArrayList 中,其中 TaggedFriends 类将设置和获取方法.

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.

我现在在名为 MainFragment 的 Fragment 类中工作.在这里,我将值存储到 FacebookCallback 会话中的 taggableFriends 变量中.但我无法访问它到任何其他地方我试图将它存储到 SharedPreferences 中,但是当我尝试存储时,它返回空值.

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.

这是我的 MainFragment 完整代码

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

        }
    }
}

请注意 FacebookCallBack --> onSuccess() 方法内部.我在那里存储变量 taggedFriends

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

紧接着,我将 taggedFriends 存储到 SharedPreferences 中.但在那个地方,taggedFriends 变量为空.它不包含任何东西.我用Logcat检查过.

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.

在 onSuccess() 方法内部,它的值在那里,当我使用该方法时,它为空.有什么问题?

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

推荐答案

Graph API 调用是异步执行的,即在单独的线程中执行.看起来当您尝试将值存储在 SharedPreferences 中时,异步调用尚未完成并且您得到 null.尝试将 SharedPreferences 部分中的存储移动到 onCompleted 方法内,然后将其添加到 ArrayList 中.

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.

这篇关于为什么我不能在 FacebookCallback 之外使用我的 ArrayList 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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