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();
}
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
.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With