Java 如何在 Android 上的片段中使用共享首选项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21720089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:15:44  来源:igfitidea点击:

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

javaandroidfacebookandroid-fragmentssharedpreferences

提问by anu_r

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?

我有一个片段,我想将 Facebook id 存储在共享首选项中。我无法在获取首选项功能中编写私有模式。而且我想在另一个片段中访问这个共享首选项。我怎么能这样做?

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

采纳答案by kevz

Use Shared Preferencesinside a Fragment; see below.

使用Shared PreferencesFragment; 见下文。

First write in SharedPreferences:

首先写入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.

这里 id 是包含您获得的 Facebook id 的字符串,0 表示 private_mode。

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

其次,读取存储SharedPreference在另一个中的 Facebook id 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.

这里 empty 是如果 facebook_id 在里面为 null 则返回的默认值SharedPreference

回答by Karthick pop

  • 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);
    }
    }
    
  • 创建一个单独的会话类:

    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 getsessionidmethod to get that ID.

要保存 ID 时调用 save 方法。然后,以相同的方式调用该getsessionid方法以获取该 ID。

回答by Sujith Thankachan

Update your SavePreferencesmethod as follows:

更新您的SavePreferences方法如下:

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

回答by user896033

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

回答by Aditya Vyas-Lakhan

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

回答by Amitsharma

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

尝试使用此代码。这已经足够了Shared preference,无论您在活动中工作还是在Fragment. Shared preferenceActivity 或Fragment.

For more click here

更多请点击这里