片段中的 Android 共享首选项

我正在尝试读取片段中的 SharedPreferences。我的代码就是我用来获取任何其他活动中的首选项的代码。

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

我出错了

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

我已经尝试按照这些链接,但没有运气 通过静态方法访问 SharedPreferences静态共享首选项 感谢您的解决方案。

156766 次浏览

The method getSharedPreferences is a method of the Context object, so just calling getSharedPreferences from a Fragment will not work...because it is not a Context! (Activity is an extension of Context, so we can call getSharedPreferences from it).

So you have to get your applications Context by

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

As a note of caution this answer provided by the user above me is correct.

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

However, if you attempt to get anything in the fragment before onAttach is called getActivity() will return null.

The marked answer didn't work for me, I had to use

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

EDIT:

Or just try removing the this:

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

You can make the SharedPrefences in onAttach method of fragment like this:

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

This did the trick for me

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

Check here https://developer.android.com/guide/topics/ui/settings.html#ReadingPrefs

getActivity() and onAttach() didnot help me in same situation
maybe I did something wrong
but! I found another decision
I have created a field Context thisContext inside my Fragment
And got a current context from method onCreateView
and now I can work with shared pref from fragment

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

To define the preference in Fragment: SharedPreferences pref = getActivity().getSharedPreferences("CargaDatosCR",Context.MODE_PRIVATE); editor.putString("credi_credito",cre); editor.commit();

To call another activity or fragment the preference data: SharedPreferences pref = getActivity().getSharedPreferences("CargaDatosCR", Context.MODE_PRIVATE); credit=pref.getString("credi_credito",""); if(credit.isNotEmpty)...

It is possible to get a context from within a Fragment

Just do

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

You may also attached an AndroidViewModel in the onCreateView method that implements a method that returns the application context

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
}
}

Maybe this is helpfull to someone after few years. New way, on Androidx, of getting SharedPreferences() inside fragment is to implement into gradle dependencies

implementation "androidx.preference:preference:1.1.1"

and then, inside fragment call

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

use requiredactivity in fragment kotlin

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

Get Current Date and Time or get each every attributes from it:

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

Given a fragment, you can setup your SharedPreferences like so:

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

Let me know if you have any further questions.