SharedPreference values not retrieved in different Activities

…衆ロ難τιáo~ 提交于 2019-12-11 18:27:06

问题


I have three Activities.When my application opens the first time ActivityOne is opened and I am saving a value in preference and using Intent I go to ActivityThree and replace one Fragment in layout.
This is code for saving value in ActivityOne

     SharedPreferences prefs;
          SharedPreferences.Editor edit;
    prefs=MainActivity.this.getSharedPreferences("myPrefs",MODE_PRIVATE); 
    edit=prefs.edit();  
@Override
public void onResponse(JSONObject response) {        
       try {
              saveToken = response.getString("token");
             edit.putString("token", saveToken);
             Log.i("Login", saveToken);
              edit.apply()
                 }
        catch(JSONException e)
        {
        }

I retrieve the value from Preference and getting correct value in Fragment of ActivityThree as

SharedPreferences prefs;
 prefs=getActivity().getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
            myToken = prefs.getString("token", "empty"); 

When application is closed I am removing the value from preference.

AlertDialog.Builder builder = new AlertDialog.Builder(ActivityTwo.this);
            builder.setTitle("Exit App");
            builder.setMessage("Do you really want to Exit ?");
            builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                        edit=prefs.edit();
                    edit.remove("token");
                    edit.apply();
                    finish();
                }
            });  

When my application is open later ActivityTwo is opened.I am retrieving the one value from preference and after successfull login I an saving one value in Preference.
This is code for retrieving value from preference in ActivityTwo

SharedPreferences prefs,prefs1;
        SharedPreferences.Editor edit;
      prefs1 = ActivityTwo.this.getSharedPreferences("restKey",MODE_PRIVATE);
            key=prefs1.getString("key","empty");  

At same time after Login I am saving one value in Preference as

SharedPreferences prefs,prefs1;
        SharedPreferences.Editor edit;
 prefs = ActivityTwo.this.getSharedPreferences("myPrefs", MODE_PRIVATE);
        edit = prefs.edit();
 @Override
                    public void onResponse(JSONObject response) {

                        try {
                            saveToken = response.getString("token");
                            edit.putString("token", saveToken);
                            edit.apply();
                         }
catch(JSONEceeption e)
{
}  

After Login using Intent I open ActivityThree and replace one Fragment and retrieve value from Preference as

SharedPreferences prefs;
 prefs=getActivity().getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
            myToken = prefs.getString("token", "empty");  

But I am not getting any value in it ?


回答1:


Try using the PreferenceManager to geth the default shared preference.

import android.preference.PreferenceManager;


public static SharedPreferences getPref(Context context) {
    return PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
}

public static SharedPreferences.Editor getEditor(Context context) {
    return getPref(context).edit();
}

to use it just call the same way as you did currently

getPref(getActivity()) .getString("token", "empty");  //to read.

and

getEditor(getActivity()).putString("token", "empty").commit(); // to write.



回答2:


Just simple no need to do more work use below Preference util class in you application.

public class PrefUtils {

    //preference file
    private static final String DEFAULT_PREFS = "GIVE YOUR APP NAME HERE";

    //any numeric getter method will return -1 as default value
    private static final int DEFAULT_NUMERIC_VALUE = -1;

    //any string getter method will return empty string as default value
    private static final String DEFAULT_STRING_VALUE = "";

    public static void setString(Context mContext,String key, @Nullable String value) {
        SharedPreferences prefs = mContext.getSharedPreferences(DEFAULT_PREFS, Context.MODE_PRIVATE);
        Editor editor = prefs.edit();
        editor.putString(key, value);
        editor.apply();
    }

    public static String getString(Context mContext,String key) {
        SharedPreferences prefs = mContext.getSharedPreferences(DEFAULT_PREFS, Context.MODE_PRIVATE);
        return prefs.getString(key, DEFAULT_STRING_VALUE);
    }

    public static void setBoolean(Context mContext,String key, boolean value) {
        SharedPreferences prefs = mContext.getSharedPreferences(DEFAULT_PREFS, Context.MODE_PRIVATE);
        Editor editor = prefs.edit();
        editor.putBoolean(key, value);
        editor.apply();
    }

    public static boolean getBoolean(Context mContext,String key) {
        SharedPreferences prefs = mContext.getSharedPreferences(DEFAULT_PREFS, Context.MODE_PRIVATE);
        return prefs.getBoolean(key, false);
    }

    public static void setLong(Context mContext,String key, long value) {
        SharedPreferences prefs = mContext.getSharedPreferences(DEFAULT_PREFS, Context.MODE_PRIVATE);
        Editor editor = prefs.edit();
        editor.putLong(key, value);
        editor.apply();
    }

    public static long getLong(Context mContext,String key) {
        SharedPreferences prefs = mContext.getSharedPreferences(DEFAULT_PREFS, Context.MODE_PRIVATE);
        return prefs.getLong(key, DEFAULT_NUMERIC_VALUE);
    }

    public static void setInteger(Context mContext,String key, int value) {
        SharedPreferences prefs = mContext.getSharedPreferences(DEFAULT_PREFS, Context.MODE_PRIVATE);
        Editor editor = prefs.edit();
        editor.putInt(key, value);
        editor.apply();
    }

    public static int getInteger(Context mContext,String key) {
        SharedPreferences prefs = mContext.getSharedPreferences(DEFAULT_PREFS, Context.MODE_PRIVATE);
        return prefs.getInt(key, DEFAULT_NUMERIC_VALUE);
    }

    public static void setFloat(Context mContext,String key, float value) {
        SharedPreferences prefs = mContext.getSharedPreferences(DEFAULT_PREFS, Context.MODE_PRIVATE);
        Editor editor = prefs.edit();
        editor.putFloat(key, value);
        editor.apply();
    }

    public static float getFloat(Context mContext,String key) {
        SharedPreferences prefs = mContext.getSharedPreferences(DEFAULT_PREFS, Context.MODE_PRIVATE);
        return prefs.getFloat(key, (float) DEFAULT_NUMERIC_VALUE);
    }

    public static void setObject(Context mContext,String key, @NonNull Object value) {
        SharedPreferences prefs = mContext.getSharedPreferences(DEFAULT_PREFS, Context.MODE_PRIVATE);
        Editor editor = prefs.edit();
        editor.putString(key, mGson.toJson(value));
        editor.apply();
    }

    @Nullable
    public static <T> T getObject(Context mContext,String key, Class<T> pojoClass) {
        SharedPreferences prefs = mContext.getSharedPreferences(DEFAULT_PREFS, Context.MODE_PRIVATE);
        String jsonString = prefs.getString(key, null);
        if (jsonString == null) {
            return null;
        }
        return mGson.fromJson(jsonString, pojoClass);
    }

    public static Map<String, ?> getAll(Context mContext) {
        SharedPreferences prefs = mContext.getSharedPreferences(DEFAULT_PREFS, Context.MODE_PRIVATE);
        return prefs.getAll();
    }

    public static void removeKey(Context mContext,String key) {
        SharedPreferences prefs = mContext.getSharedPreferences(DEFAULT_PREFS, Context.MODE_PRIVATE);
        Editor editor = prefs.edit();
        editor.remove(key);
        editor.apply();
    }

    public static void clearAll(Context mContext) {
        SharedPreferences prefs = mContext.getSharedPreferences(DEFAULT_PREFS, Context.MODE_PRIVATE);
        Editor editor = prefs.edit();
        editor.clear();
        editor.apply();
    }

    public static boolean setPreferenceArray(Context mContext, String key,
                                             ArrayList<String> array) {
        SharedPreferences prefs = mContext.getSharedPreferences(DEFAULT_PREFS, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt(key + "_size", array.size());
        for (int i = 0; i < array.size(); i++)
            editor.putString(key + "_" + i, array.get(i));
        return editor.commit();
    }

    public static ArrayList<String> getPreferenceArray(Context mContext,String key) {
        SharedPreferences prefs = mContext.getSharedPreferences(DEFAULT_PREFS, Context.MODE_PRIVATE);
        int size = prefs.getInt(key + "_size", 0);
        ArrayList<String> array = new ArrayList<>(size);
        for (int i = 0; i < size; i++)
            array.add(prefs.getString(key + "_" + i, null));
        return array;
    }
}

Ex. You need to do following things to use above class.

(1)Store value into preference like.

PrefUtils.setString(context,"Key","Value you need to store");

(2)Retrive value from the preference.

PrefUtils.getString(context,"Key");


来源:https://stackoverflow.com/questions/50248485/sharedpreference-values-not-retrieved-in-different-activities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!