Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
                        }
like image 744
anu_r Avatar asked Nov 28 '22 01:11

anu_r


2 Answers

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.

like image 60
kevz Avatar answered Dec 04 '22 13:12

kevz


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);
like image 25
Aditya Vyas-Lakhan Avatar answered Dec 04 '22 13:12

Aditya Vyas-Lakhan