重新打开应用后Facebook登录数据丢失

时间:2016-08-06 07:38:19

标签: android facebook facebook-graph-api

我在片段中添加了Facebook登录代码。一切正常,我可以登录我的应用程序但是当我在登录后更改片段或重新打开应用程序时,每个数据都消失了,即电子邮件,姓名,birthday.it没有显示任何数据。那么,我该怎么做才能保存这些数据数据

    public class ProfileFragment extends Fragment{
    ProfileTracker profileTracker;
    RelativeLayout fbbg;
    RelativeLayout rl;
    LoginButton btnLogin;
    CallbackManager callbackManager;
    AccessTokenTracker accessTokenTracker;
    CircleImageView profilePicture;
    TextView email;
    TextView gender;
    TextView facebookName;
    TextView birthday;
    SharedPreferences pref;

    public static final List<String> mPermissions = new ArrayList<String>() {{
    add("public_profile");
    add("email");
    add("user_photos");
    add("user_birthday");
}};

    @Nullable
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstantState) {
    View view =  inflater.inflate(R.layout.profile, container, false);
    FacebookSdk.sdkInitialize(getActivity());
    btnLogin = (LoginButton)view.findViewById(R.id.view);

    email = (TextView)view.findViewById(R.id.un2);

    facebookName = (TextView)view.findViewById(R.id.username);

    birthday = (TextView)view.findViewById(R.id.bd2);

    gender = (TextView)view.findViewById(R.id.gnd2);

    profilePicture = (CircleImageView)view.findViewById(R.id.profile_image);

    rl = (RelativeLayout) view.findViewById(R.id.rl);

    fbbg = (RelativeLayout) view.findViewById(R.id.relativeLayout);

    callbackManager = CallbackManager.Factory.create();
    btnLogin.setReadPermissions(mPermissions);
    btnLogin.setFragment(this);
    btnLogin.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {

        @Override
        public void onSuccess(LoginResult loginResult) {
            AccessToken accessToken = loginResult.getAccessToken();
            Profile profile = Profile.getCurrentProfile();
            GraphRequest request = GraphRequest.newMeRequest(
                    loginResult.getAccessToken(),
                    new GraphRequest.GraphJSONObjectCallback() {

                        @Override
                        public void onCompleted(JSONObject object, GraphResponse response) {
                            Log.d("JSON", ""+response.getJSONObject().toString());
                            try {
                                fbbg.setVisibility(View.GONE);
                                rl.setVisibility(View.VISIBLE);
                                email.setText(object.getString("email"));
                                gender.setText(object.getString("gender"));
                                facebookName.setText(object.getString("name"));
                                birthday.setText(object.getString("birthday"));
                                Glide.with(getActivity())
                                        .load("https://graph.facebook.com/" + object.getString("id") + "/picture?type=large")
                                        .into(profilePicture);
                                pref = getActivity().getSharedPreferences("", getActivity().MODE_PRIVATE);
                                SharedPreferences.Editor editor = pref.edit();
                                editor.putString("name", String.valueOf(facebookName));
                                editor.putString("email", String.valueOf(email));
                                editor.putString("gender", String.valueOf(gender));
                                editor.putString("birthday", String.valueOf(birthday));
                                editor.commit();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "id,name,email,gender,birthday");
            request.setParameters(parameters);
            request.executeAsync();

            accessTokenTracker = new AccessTokenTracker() {
                @Override
                protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken,
                                                           AccessToken currentAccessToken) {
                    if (currentAccessToken == null) {
                        facebookName.setText("");
                        email.setText("");
                        gender.setText("");
                        birthday.setText("");
                        profilePicture.setImageResource(R.drawable.user);
                    }
                }
            };
            profileTracker = new ProfileTracker() {
                @Override
                protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
                }
            };

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


        @Override
        public void onCancel() {
            Toast.makeText(getActivity(),"Cancled to Login Facebook", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(FacebookException exception) {
            Toast.makeText(getActivity(),"Error to Login Facebook", Toast.LENGTH_SHORT).show();
        }
    }); return view;
}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    pref = getActivity().getSharedPreferences("", getActivity().MODE_PRIVATE);
    pref.getString("name", "asdfgh");
    pref.getString("email", "qwerty");
    pref.getString("gender", "zxcvb");
    pref.getString("birthday", "kdhfaj");
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    callbackManager.onActivityResult(requestCode, resultCode, data);
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            onResume();
        }
    }, 2000);
}

}

After login pic After reopening app pic

4 个答案:

答案 0 :(得分:0)

@Override
public void onResume() {
    super.onResume();
    Profile profile = Profile.getCurrentProfile();
    AppEventsLogger.activateApp(getActivity());
}

无需这样做。

每当你恢复片段时,那时它就会创建你的facebook个人资料的新实例,这就是数据丢失的原因。

在简历上重新加载片段不要创建新的实例。

每当您从facebook api获取数据时,立即将其存储到共享首选项。之后,您可以随时获取该数据。

答案 1 :(得分:0)

public UpdateFragment() {
    // Required empty public constructor
}

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

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    v = inflater.inflate(R.layout.fragment_updates, container, false);

    listView = (ListView) v.findViewById(R.id.listView);

    // define your xml resources here

    return v;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setRetainInstance(true);

    loadUpdates();
}

private void loadUpdates() {

        // api call
}

}

尝试将代码嵌入此片段生命周期。它肯定会奏效。

无需添加onResume()

只需在loadUpdates()中执行您的操作;方法

答案 2 :(得分:0)

我已经使用SharedPreference修改了您的代码。 你可以试试。

        pref = getActivity().getSharedPreferences("GIVE SOME name TO FILE", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.putString("name", object.getString("name"));
        editor.putString("email", object.getString("email"));
        editor.putString("gender", object.getString("gender"));
        editor.putString("birthday", object.getString("birthday"));
        editor.apply();

从FB

成功获取用户个人资料信息后,将上述代码替换为现有代码

答案 3 :(得分:0)

我认为您的问题是SharedPreferences已使用Activity初始化。为避免在Activity销毁时您的数据丢失,您应使用ApplicationContext() 我和SharedPreference分开了这样的课程:

public class SessionManager {

// Shared Preferences reference
public SharedPreferences pref;

// Editor reference for Shared preferences
private Editor editor;

@SuppressWarnings("unused")
private Context context;
int PRIVATE_MODE = 0;
public static final String PREFER_NAME = "login";
public static final String KEY_USER_NAME = "username";

public SessionManager(Context context) {
    this.context = context;
    pref = context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
    editor = pref.edit();
}

public String getUserName() {
    return pref.getString(KEY_USER_NAME, "");
}

public void setUserName(String userName) {
    editor.putString(KEY_USER_NAME, userName);
    editor.commit();
}

Fragment中,使用以下内容初始化SharedPreferences

sessionManager = new SessionManager(getActivity.getApplicationContext());

保存您的数据:

session.setUserName(object.getString("name"));

稍后通过调用

检索数据
String userName = session.getUserName();