簡體   English   中英

Fragment 中的 Android SharedPreferences

[英]Android SharedPreferences in Fragment

我正在嘗試讀取 Fragment 中的 SharedPreferences。 我的代碼是我用來在任何其他活動中獲取首選項的代碼。

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

我得到錯誤

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

我試圖遵循這些鏈接,但沒有成功通過靜態方法靜態 SharedPreferences 訪問SharedPreferences 感謝您提供任何解決方案。

getSharedPreferences方法是Context對象的一個​​方法,因此僅從Fragment調用 getSharedPreferences 是行不通的……因為它不是 Context! (Activity 是 Context 的擴展,因此我們可以從中調用 getSharedPreferences)。

所以你必須得到你的應用程序上下文

// this = your fragment
SharedPreferences preferences = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);

標記的答案對我不起作用,我不得不使用

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

編輯:

或者只是嘗試刪除this

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

請注意,我上面的用戶提供的這個答案是正確的。

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

但是,如果您嘗試在 onAttach 調用之前獲取片段中的任何內容,則 getActivity() 將返回 null。

您可以像這樣在片段的onAttach方法中創建SharedPrefences

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

這對我有用

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

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

getActivity()onAttach()在同樣的情況下沒有幫助我
也許我做錯了什么
但! 我找到了另一個決定
我在 Fragment 中創建了一個字段Context thisContext
並從方法 onCreateView 獲得當前上下文
現在我可以使用片段中的共享首選項

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

在 Fragment 中定義首選項: SharedPreferences pref = getActivity().getSharedPreferences("CargaDatosCR",Context.MODE_PRIVATE); editor.putString("credi_credito",cre); editor.commit(); 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)... SharedPreferences pref = getActivity().getSharedPreferences("CargaDatosCR", Context.MODE_PRIVATE); credit=pref.getString("credi_credito",""); if(credit.isNotEmpty)...

給定一個片段,您可以像這樣設置 SharedPreferences:

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

如果您有任何其他問題,請告訴我。

可以從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
     }
  }

也許這對幾年后的人有幫助。 在 Androidx 上,在片段中獲取SharedPreferences()新方法是實現到gradle dependencies

implementation "androidx.preference:preference:1.1.1"

然后,在片段調用中

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

在片段 kotlin 中使用 requiredactivity

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

獲取當前日期和時間或從中獲取每個屬性:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM