How do I use shared preferences in a fragment on Android?

非 Y 不嫁゛ 提交于 2019-12-12 16:16:48

问题


I have a fragment and I want to store the Facebook id in a shared preference. I can't write mode private in the get preference function. And also I want to access this shared preference in another fragment. How can I do so?

Here is my code...

Session.openActiveSession(getActivity(), true, new Session.StatusCallback()
{
    @Override
    public void call(Session session,
                     SessionState state,
                     Exception exception) {

        if (session.isOpened()) {
            Request.executeMeRequestAsync(session,new Request.GraphUserCallback() {

                @Override
                public void onCompleted(GraphUser user, Response response) {

                    if (user != null) {
                        t = (TextView)rootView.findViewById(R.id.textView2);
                        p = (ProfilePictureView)rootView.findViewById(R.id.profilePictureView1);
                        p.setProfileId(user.getId());
                        s = user.getName();
                        t.setText(s);
                        s1 = user.getId();

                        private void SavePreferences(String key,String value)
                        {
                            SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
                            SharedPreferences.Editor editor = sharedPreferences.edit();
                            editor.putString(key, value);
                            editor.commit();
                        }

回答1:


Use Shared Preferences inside a Fragment; see below.

First write in SharedPreferences:

SharedPreferences pref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor edt = pref.edit();
edt.putString("facebook_id", id);
edt.commit();

Here id is the string containing the Facebook id which you've got, and 0 indicates private_mode.

Second, to read the Facebook id stored in SharedPreference in another Fragment:

SharedPreferences pref = getActivity().getPreferences(Context.MODE_PRIVATE);
String id = pref.getString("facebook_id", "empty");

Here empty is the default value returned if facebook_id is null inside SharedPreference.




回答2:


You can also do like,

editor = getActivity().getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE).edit();
                        editor.putString("yourtextvalueKey", test);
                        editor.commit();

and to get

prefs = getActivity().getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE);
        text = prefs.getString("yourtextvalueKey", null);



回答3:


Update your SavePreferences method as follows:

private static String MY_PREFS = "My_Preference";
private void SavePreferences(String key, String value) {
    SharedPreferences sharedPreferences = getActivity().getSharedPreferences(
            MY_PREFS, 0);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(key, value);
    editor.apply();
}



回答4:


  • Create a separate session class:

    public class Session {
    private static String PREF_NAME = "Memory";
    private static String FBID = "FBID ";
    public static boolean saveSessionId(String FBID , Context context) {
    Editor editor = context.getSharedPreferences(PREF_NAME, 0).edit();
    editor.putString(FBID , FBID);
    return editor.commit();
    }
    
    public static String getSessionId(Context context) {
    SharedPreferences savedSession = context.getSharedPreferences(
            PREF_NAME, 0);
    return savedSession.getString(FBID , null);
    }
    }
    

Call the save method when you want to save the ID. Then, in the same way, call the getsessionid method to get that ID.




回答5:


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    getSharedPrefs();
}

private void getSharedPrefs() {
    sharedpreferences = getActivity().getSharedPreferences(
            Data.MY_PREFERENCES, Context.MODE_PRIVATE);

    // check for all to be loaded here
    boolean isValid = false;

    int posImage = 0;

    if (sharedpreferences.contains(Data.COLUMN_IMAGENUMBER)) {
        posImage = sharedpreferences.getInt(Data.COLUMN_IMAGENUMBER, 0);
        if (posImage >= 0 || posImage < Data.PICS.length) {
            isValid = true;
        }
    } else {
        isValid = false;
    }
}

@Override
public void onStop() {
    super.onStop();
    Editor editor = sharedpreferences.edit();
    editor.putInt(Data.COLUMN_IMAGENUMBER, cv.currentPuzzleImagePosition);
    editor.apply();
}



回答6:


Try with this code. This is enough for this Shared preference, and it works either you work in activity or Fragment. Shared preference can not reflect or can not effective either Activity or Fragment.

For more click here



来源:https://stackoverflow.com/questions/21720089/how-do-i-use-shared-preferences-in-a-fragment-on-android

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