【问题标题】:Android SharedPreferences in Fragment片段中的Android SharedPreferences
【发布时间】:2025-11-28 10:25:02
【问题描述】:

我正在尝试读取 Fragment 中的 SharedPreferences。我的代码用于在任何其他 Activity 中获取首选项。

     SharedPreferences preferences = getSharedPreferences("pref", 0);

我得到错误

    Cannot make a static reference to the non-static method getSharedPreferences(String, int) from the type ContextWrapper    

我尝试关注这些链接,但没有运气Accessing SharedPreferences through static methodsStatic SharedPreferences。感谢您的任何解决方案。

【问题讨论】:

    标签: android android-fragments sharedpreferences


    【解决方案1】:

    方法getSharedPreferencesContext 对象的方法,所以仅仅从Fragment 调用getSharedPreferences 是行不通的……因为它不是上下文! (Activity 是 Context 的扩展,所以我们可以从中调用 getSharedPreferences)。

    所以你必须通过

    获取你的应用程序上下文
    // this = your fragment
    SharedPreferences preferences = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
    

    【讨论】:

    • getSharedPreferences("pref",0);零(0)意味着什么私有/公共?
    • @Kailas 正确,模式,即 WORLD_READABLE 等。 developer.android.com/reference/android/content/…, int)
    • 0 类似于 MODE_PRIVATE(或 Context.MODE_PRIVATE,如果在不是 Context 扩展的类中使用,例如 Fragment)。这意味着只有相关应用程序才能访问首选项。您不应该使用 WORLD_READABLE 或 WORLD_WRITEABLE,因为它们在 API 17+ 中已被弃用,更不用说安全威胁了。
    • 在做this.getActivity().getShared..时这个this关键字是否必要?
    • @Subby 不,永远不需要明确调用“this”。我这样做是出于个人喜好,因为我讨厌模棱两可的方法调用。唯一需要“this”的情况是,当您在匿名内部类/接口中超出其范围时尝试访问父非静态对象。
    【解决方案2】:

    标记的答案对我不起作用,我不得不使用

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
    

    编辑:

    或者只是尝试删除this

    SharedPreferences prefs = getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
    

    【讨论】:

    • 标记的答案对您不起作用,因为您正在访问默认的共享首选项。更好的设计是将您的偏好不作为共享对象存储,而是存储在单独的私人空间中,这就是这里的问题和答案。
    【解决方案3】:

    请注意,我上面的用户提供的这个答案是正确的。

    SharedPreferences preferences = this.getActivity().getSharedPreferences("pref",0);
    

    但是,如果您在调用 onAttach 之前尝试获取片段中的任何内容,getActivity() 将返回 null。

    【讨论】:

      【解决方案4】:

      您可以像这样在片段的onAttach 方法中创建SharedPrefences

      @Override
      public void onAttach(Context context) {
          super.onAttach(context);
          SharedPreferences preferences = context.getSharedPreferences("pref", 0);
      }
      

      【讨论】:

        【解决方案5】:

        这对我有用

        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
        

        在这里查看https://developer.android.com/guide/topics/ui/settings.html#ReadingPrefs

        【讨论】:

          【解决方案6】:

          getActivity()onAttach() 在同样的情况下没有帮助我
          也许我做错了什么
          但!我找到了另一个决定
          我在 Fragment 中创建了一个字段 Context thisContext
          并从方法 onCreateView
          获得当前上下文 现在我可以使用片段中的共享首选项

          public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                                       Bundle savedInstanceState) {   
          ...   
          thisContext = container.getContext();   
          ...   
          }
          

          【讨论】:

            【解决方案7】:

            在 Fragment 中定义偏好: SharedPreferences pref = getActivity().getSharedPreferences("CargaDatosCR",Context.MODE_PRIVATE); editor.putString("credi_credito",cre); editor.commit();

            调用另一个活动或分段偏好数据: SharedPreferences pref = getActivity().getSharedPreferences("CargaDatosCR", Context.MODE_PRIVATE); credit=pref.getString("credi_credito",""); if(credit.isNotEmpty)...

            【讨论】:

              【解决方案8】:

              也许几年后这对某人有帮助。 在 Androidx 上,获取 SharedPreferences() 内部片段的新方法是实现到 gradle dependencies

              implementation "androidx.preference:preference:1.1.1"
              

              然后,在片段调用中

              SharedPreferences preferences;
              preferences = androidx.preference.PreferenceManager.getDefaultSharedPreferences(getActivity());
              

              【讨论】:

                【解决方案9】:

                给定一个片段,您可以像这样设置您的 SharedPreferences:

                val sharedPreferences = activity!!.applicationContext.getSharedPreferences(TAG,   Context.MODE_PRIVATE) // kotlin
                SharedPreferences sharedPreferences = getActivity().getApplicationContext().getSharedPreferences(TAG,   Context.MODE_PRIVATE); // java
                

                如果您还有其他问题,请告诉我。

                【讨论】:

                  【解决方案10】:

                  可以从Fragment 中获取上下文

                  做事

                  public class YourFragment extends Fragment {
                  
                      public View onCreateView(@NonNull LayoutInflater inflater,
                                               ViewGroup container, Bundle savedInstanceState) {
                          final View root = inflater.inflate(R.layout.yout_fragment_layout, container, false);
                          // get context here
                          Context context = getContext();
                          // do as you please with the context
                  
                  
                          // if you decide to go with second option
                          SomeViewModel someViewModel = ViewModelProviders.of(this).get(SomeViewModel.class);
                          Context context = homeViewModel.getContext();
                          // do as you please with the context
                          return root;
                      }
                  }
                  

                  您还可以在onCreateView 方法中附加一个AndroidViewModel,该方法实现了一个返回应用程序上下文的方法

                  public class SomeViewModel extends AndroidViewModel {
                  
                      private MutableLiveData<ArrayList<String>> someMutableData;
                      Context context;
                  
                      public SomeViewModel(Application application) {
                          super(application);
                          context = getApplication().getApplicationContext();
                          someMutableData = new MutableLiveData<>();
                          .
                          .
                       }
                  
                       public Context getContext() {
                           return context
                       }
                    }
                  

                  【讨论】:

                    【解决方案11】:

                    在片段 kotlin 中使用 requiredactivity

                     val sharedPreferences = requireActivity().getSharedPreferences(loginmasuk.LOGIN_DATA, Context.MODE_PRIVATE)
                    

                    【讨论】:

                      【解决方案12】:

                      获取当前日期和时间或从中获取每个属性:

                      import java.sql.Date;
                      import java.text.SimpleDateFormat;
                      import java.util.Calendar;
                      
                      String timeStamp = new SimpleDateFormat( "dd/MM/yy   HH:mm:ss").format(Calendar.getInstance().getTime());
                      
                              String timeStamp1 = new SimpleDateFormat("dd/MM/yy").format(Calendar.getInstance().getTime());
                              String timeStamp2 = new SimpleDateFormat("dd").format(Calendar.getInstance().getTime());
                              System.out.print(timeStamp1);
                              if(timeStamp1.contains("10/03/21")) {
                                  System.out.print("\ntrue");
                              }
                              else {
                                  System.out.print("false");
                              }
                      

                      【讨论】: