Значения SharedPreference не получены в разных действиях - PullRequest
0 голосов
/ 09 мая 2018

У меня есть три Activities. Когда мое приложение открывается в первый раз, когда открывается ActivityOne, и я сохраняю значение в настройках и с помощью Intent я перехожу к ActivityThree и заменяю один Fragment в макете.
Это код для сохранения значения в 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)
        {
        }

Я получаю значение из Предпочтения и получаю правильное значение во Фрагменте ActivityThree как

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

Когда приложение закрыто, я удаляю значение из предпочтения.

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

Когда мое приложение открывается позже, открывается ActivityTwo. Я получаю одно значение из предпочтения и после успешного входа в систему сохраняю одно значение в Предпочтении.
Это код для получения значения из предпочтения в ActivityTwo

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

В то же время после входа я сохраняю одно значение в настройках как

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

После входа в систему с помощью намерения я открываю ActivityThree и заменяю один фрагмент и извлекаю значение из предпочтения как

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

Но я не получаю никакого значения?

Ответы [ 2 ]

0 голосов
/ 09 мая 2018

Просто просто, не нужно больше работать, используя класс утилит Preference в вашем приложении.

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. Вы должны сделать следующие вещи, чтобы использовать выше класс.

(1) Сохранить значение в предпочтение, как.

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

(2) Извлечь значение из предпочтения.

PrefUtils.getString(context,"Key");
0 голосов
/ 09 мая 2018

Попробуйте использовать PreferenceManager для получения общих настроек по умолчанию.

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

, чтобы использовать его, просто позвоните так же, как вы в настоящее время

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

и

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