Android Shared preferences do tworzenia aktywności jednorazowej (przykład) [zamknięte]

zamknięte. to pytanie nie spełnia wytycznych dotyczących przepełnienia stosu . Obecnie nie przyjmuje odpowiedzi.

chcesz poprawić to pytanie? Update the pytanie więc to on-topic {[3] } dla przepełnienia stosu.

Zamknięte 4 lata temu .

Popraw to pytanie

Mam trzy czynności A, B I C gdzie A i B są formularzami i po wypełnieniu i zapisaniu danych formularza w bazie danych (SQLITE). Używam intencji od A do B, a potem od B Do C. za każdym razem, gdy otwieram moją aplikację chcę C jako mój ekran główny, a nie A i b już.

Myślę, że wspólne preferencje by na to zadziałały, ale nie mogę znaleźć dobrego przykładu, aby dać mi miejsce startowe. Każda pomoc będzie mile widziana.

Author: Vaibhav Bisht, 2014-04-12

15 answers

Ustawianie wartości w preferencjach:

// MY_PREFS_NAME - a static String variable like: 
//public static final String MY_PREFS_NAME = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
 editor.putString("name", "Elena");
 editor.putInt("idName", 12);
 editor.apply();

Pobieranie danych z preferencji:

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.

Więcej informacji:

Korzystanie Ze Współdzielonych Preferencji

Wspólne Preferencje

 649
Author: Jorgesys,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-02-08 20:03:30

Create SharedPreferences

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE); 
Editor editor = pref.edit();

Przechowywanie danych jako pary klucz / wartość

editor.putBoolean("key_name1", true);           // Saving boolean - true/false
editor.putInt("key_name2", "int value");        // Saving integer
editor.putFloat("key_name3", "float value");    // Saving float
editor.putLong("key_name4", "long value");      // Saving long
editor.putString("key_name5", "string value");  // Saving string

// Save the changes in SharedPreferences
editor.apply(); // commit changes

Get SharedPreferences data

// Jeśli wartość dla klucza nie istnieje, zwróć drugą wartość param-w tym przypadku null

boolean userFirstLogin= pref.getBoolean("key_name1", true);  // getting boolean
int pageNumber=pref.getInt("key_name2", 0);             // getting Integer
float amount=pref.getFloat("key_name3", null);          // getting Float
long distance=pref.getLong("key_name4", null);          // getting Long
String email=pref.getString("key_name5", null);         // getting String

Usuwanie wartości klucza z SharedPreferences

editor.remove("key_name3"); // will delete key key_name3
editor.remove("key_name4"); // will delete key key_name4

// Save the changes in SharedPreferences
editor.apply(); // commit changes

Wyczyść wszystkie dane z SharedPreferences

 editor.clear();
 editor.apply(); // commit changes
 108
Author: Krausz Lóránt Szilveszter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-10-01 14:33:23

Jak Zainializować?

// 0 - for private mode`
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); 

Editor editor = pref.edit();

Jak przechowywać dane w preferencjach współdzielonych?

editor.putString("key_name", "string value"); // Storing string

Lub

editor.putInt("key_name", "int value"); //Storing integer

I nie zapomnij zastosować:

editor.apply();

Jak odzyskać dane ze współdzielonych preferencji ?

pref.getString("key_name", null); // getting String

pref.getInt("key_name", 0); // getting Integer

Mam nadzieję, że to pomoże U:)

 44
Author: Omi Sparky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-04 02:05:17

Możesz utworzyć własną klasę SharedPreference

public class YourPreference {   
    private static YourPreference yourPreference;
    private SharedPreferences sharedPreferences;

    public static YourPreference getInstance(Context context) {
        if (yourPreference == null) {
            yourPreference = new YourPreference(context);
        }
        return yourPreference;
    }

    private YourPreference(Context context) {
        sharedPreferences = context.getSharedPreferences("YourCustomNamedPreference",Context.MODE_PRIVATE);
    }

    public void saveData(String key,String value) {
        SharedPreferences.Editor prefsEditor = sharedPreferences.edit();
        prefsEditor .putString(key, value);
        prefsEditor.commit();           
    }

    public String getData(String key) {
        if (sharedPreferences!= null) {
           return sharedPreferences.getString(key, "");
        }
        return "";         
    }
}

Możesz otrzymać instancję Prefrence w postaci:

YourPreference yourPrefrence = YourPreference.getInstance(context);
yourPreference.saveData(YOUR_KEY,YOUR_VALUE);

String value = yourPreference.getData(YOUR_KEY);
 21
Author: Rahul Parihar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-23 18:40:19

Wszystkie powyższe przykłady uznałem za zbyt mylące, więc napisałem własne. Fragmenty kodu są w porządku, jeśli wiesz, co robisz, ale co z ludźmi takimi jak ja, którzy nie wiedzą?

Chcesz zamiast tego rozwiązanie cut-n-paste? No i jest!

Utwórz nowy plik java i nazwij go Keystore. Następnie wklej ten kod:

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;

public class Keystore { //Did you remember to vote up my example?
    private static Keystore store;
    private SharedPreferences SP;
    private static String filename="Keys";

private Keystore(Context context) {
    SP = context.getApplicationContext().getSharedPreferences(filename,0);
}

public static Keystore getInstance(Context context) {
    if (store == null) {
        Log.v("Keystore","NEW STORE");
        store = new Keystore(context);
    }
    return store;
}

public void put(String key, String value) {//Log.v("Keystore","PUT "+key+" "+value);
    Editor editor = SP.edit();
    editor.putString(key, value);
    editor.commit(); // Stop everything and do an immediate save!
    // editor.apply();//Keep going and save when you are not busy - Available only in APIs 9 and above.  This is the preferred way of saving.
}

public String get(String key) {//Log.v("Keystore","GET from "+key);
    return SP.getString(key, null);

}

public int getInt(String key) {//Log.v("Keystore","GET INT from "+key);
    return SP.getInt(key, 0);
}

public void putInt(String key, int num) {//Log.v("Keystore","PUT INT "+key+" "+String.valueOf(num));
    Editor editor = SP.edit();

    editor.putInt(key, num);
    editor.commit();
}


public void clear(){ // Delete all shared preferences
    Editor editor = SP.edit();

    editor.clear();
    editor.commit();
}

public void remove(){ // Delete only the shared preference that you want
    Editor editor = SP.edit();

    editor.remove(filename);
    editor.commit();
}
}

Zapisz ten plik i zapomnij o nim. Skończyłeś z tym. Teraz wróć do swojej aktywności i używaj jej w ten sposób:

public class YourClass extends Activity{

private Keystore store;//Holds our key pairs

public YourSub(Context context){
    store = Keystore.getInstance(context);//Creates or Gets our key pairs.  You MUST have access to current context!

    int= store.getInt("key name to get int value");
    string = store.get("key name to get string value");

    store.putInt("key name to store int value",int_var);
    store.put("key name to store string value",string_var);
    }
}
 18
Author: R M,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-29 03:34:42

Shared Preferences są plikami XML do przechowywania prywatnych prymitywnych danych w parach klucz-wartość. Typy danych zawierają Booleans , pływaki, ints, Longi i struny .

Gdy chcemy zapisać dane, które są dostępne w całej aplikacji, jednym ze sposobów jest zapisanie ich w zmiennej globalnej. Ale zniknie po zamknięciu aplikacji. Innym i zalecanym sposobem jest zapisywanie w SharedPreference. Dane zapisane w pliku SharedPreferences to dostępny w całej aplikacji i utrzymuje się nawet po zamknięciu aplikacji lub ponownym uruchomieniu.

SharedPreferences zapisuje dane w parze klucz-wartość i mogą być dostępne w ten sam sposób.

Możesz utworzyć obiekt SharedPreferences używając dwóch metod,

1).getSharedPreferences(): za pomocą tej metody można utworzyć wiele SharedPreferences.i jego pierwsze parametry w nazwie SharedPreferences.

2).getPreferences () : Za pomocą tej metody można utworzyć pojedynczy SharedPreferences.

Przechowywanie Danych

Dodaj deklarację zmiennej / Utwórz plik preferencji

public static final String PREFERENCES_FILE_NAME = "MyAppPreferences";

Pobieranie uchwytu do nazwy pliku (za pomocą getSharedPreferences)

SharedPreferences settingsfile= getSharedPreferences(PREFERENCES_FILE_NAME,0);

Otwórz Edytor i dodaj pary klucz-wartość

SharedPreferences.Editor myeditor = settingsfile.edit(); 
myeditor.putBoolean("IITAMIYO", true); 
myeditor.putFloat("VOLUME", 0.7)
myeditor.putInt("BORDER", 2)
myeditor.putLong("SIZE", 12345678910L)
myeditor.putString("Name", "Amiyo")
myeditor.apply(); 

Nie zapomnij zastosować / zapisać za pomocą myeditor.apply(), Jak pokazano powyżej.

Pobieranie Danych

 SharedPreferences mysettings= getSharedPreferences(PREFERENCES_FILE_NAME, 0);
IITAMIYO = mysettings.getBoolean("IITAMIYO", false); 
//returns value for the given key. 
//second parameter gives the default value if no user preference found
// (set to false in above case)
VOLUME = mysettings.getFloat("VOLUME", 0.5) 
//0.5 being the default value if no volume preferences found
// and similarly there are get methods for other data types
 15
Author: IntelliJ Amiya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-30 05:44:56
public class Preferences {

public static final String PREF_NAME = "your preferences name";

@SuppressWarnings("deprecation")
public static final int MODE = Context.MODE_WORLD_WRITEABLE;

public static final String USER_ID = "USER_ID_NEW";
public static final String USER_NAME = "USER_NAME";

public static final String NAME = "NAME";
public static final String EMAIL = "EMAIL";
public static final String PHONE = "PHONE";
public static final String address = "address";

public static void writeBoolean(Context context, String key, boolean value) {
    getEditor(context).putBoolean(key, value).commit();
}

public static boolean readBoolean(Context context, String key,
        boolean defValue) {
    return getPreferences(context).getBoolean(key, defValue);
}

public static void writeInteger(Context context, String key, int value) {
    getEditor(context).putInt(key, value).commit();

}

public static int readInteger(Context context, String key, int defValue) {
    return getPreferences(context).getInt(key, defValue);
}

public static void writeString(Context context, String key, String value) {
    getEditor(context).putString(key, value).commit();

}

public static String readString(Context context, String key, String defValue) {
    return getPreferences(context).getString(key, defValue);
}

public static void writeFloat(Context context, String key, float value) {
    getEditor(context).putFloat(key, value).commit();
}

public static float readFloat(Context context, String key, float defValue) {
    return getPreferences(context).getFloat(key, defValue);
}

public static void writeLong(Context context, String key, long value) {
    getEditor(context).putLong(key, value).commit();
}

public static long readLong(Context context, String key, long defValue) {
    return getPreferences(context).getLong(key, defValue);
}

public static SharedPreferences getPreferences(Context context) {
    return context.getSharedPreferences(PREF_NAME, MODE);
}

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

}

****Użyj preferencji do zapisu wartości za pomocą: - * * * *

Preferences.writeString(getApplicationContext(),
                    Preferences.NAME, "dev");

****Użyj preferencji, aby odczytać wartość za pomocą: - * * * *

Preferences.readString(getApplicationContext(), Preferences.NAME,
                    "");
 13
Author: smit modi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-24 20:54:43

Najlepszy sposób tworzenia SharedPreference i do użytku globalnego musisz utworzyć klasę jak poniżej:

public class PreferenceHelperDemo {
    private final SharedPreferences mPrefs;

    public PreferenceHelperDemo(Context context) {
        mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
    }

    private String PREF_Key= "Key";

    public String getKey() {
        String str = mPrefs.getString(PREF_Key, "");
        return str;
    }

    public void setKey(String pREF_Key) {
        Editor mEditor = mPrefs.edit();
        mEditor.putString(PREF_Key, pREF_Key);
        mEditor.apply();
    }

}
 8
Author: varotariya vajsi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-05-02 07:40:55
SharedPreferences mPref;
SharedPreferences.Editor editor;

public SharedPrefrences(Context mContext) {
    mPref = mContext.getSharedPreferences(Constant.SharedPreferences, Context.MODE_PRIVATE);
    editor=mPref.edit();
}

public void setLocation(String latitude, String longitude) {
    SharedPreferences.Editor editor = mPref.edit();
    editor.putString("latitude", latitude);
    editor.putString("longitude", longitude);
    editor.apply();
}

public String getLatitude() {
    return mPref.getString("latitude", "");
}

public String getLongitude() {
    return mPref.getString("longitude", "");
}

public void setGCM(String gcm_id, String device_id) {
     editor.putString("gcm_id", gcm_id);
    editor.putString("device_id", device_id);
    editor.apply();
}

public String getGCMId() {
    return mPref.getString("gcm_id", "");
}

public String getDeviceId() {
    return mPref.getString("device_id", "");
}


public void setUserData(User user){

    Gson gson = new Gson();
    String json = gson.toJson(user);
    editor.putString("user", json);
    editor.apply();
}
public User getUserData(){
    Gson gson = new Gson();
    String json = mPref.getString("user", "");
    User user = gson.fromJson(json, User.class);
    return user;
}

public void setSocialMediaStatus(SocialMedialStatus status){

    Gson gson = new Gson();
    String json = gson.toJson(status);
    editor.putString("status", json);
    editor.apply();
}
public SocialMedialStatus getSocialMediaStatus(){
    Gson gson = new Gson();
    String json = mPref.getString("status", "");
    SocialMedialStatus status = gson.fromJson(json, SocialMedialStatus.class);
    return status;
}
 4
Author: CHirag RAmi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-30 11:38:39

Write to Shared Preferences

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
 editor.commit(); 

Odczyt z wspólnych preferencji

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
 3
Author: Syed Junaid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-04 11:58:40
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
 1
Author: Syed Junaid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-16 03:59:37
Initialise here..
 SharedPreferences msharedpref = getSharedPreferences("msh",
                    MODE_PRIVATE);
            Editor editor = msharedpref.edit();

store data...
editor.putString("id",uida); //uida is your string to be stored
editor.commit();
finish();


fetch...
SharedPreferences prefs = this.getSharedPreferences("msh", Context.MODE_PRIVATE);
        uida = prefs.getString("id", "");
 0
Author: shweta c,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-28 11:55:30

Możesz też rzucić okiem na mój przykładowy projekt z przeszłości , napisany w tym celu. Zapisuję lokalnie nazwę i pobiera ją na żądanie użytkownika lub po uruchomieniu aplikacji.

Ale w tej chwili lepiej byłoby użyć commit (zamiast apply) do utrzymywania danych. Więcej informacji TUTAJ .

 0
Author: thodorisbais,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:03:08
        // Create object of SharedPreferences.
        SharedPreferences sharedPref = getSharedPreferences("mypref", 0);

        //now get Editor
        SharedPreferences.Editor editor = sharedPref.edit();

        //put your value
        editor.putString("name", required_Text);

        //commits your edits
        editor.commit();

       // Its used to retrieve data
       SharedPreferences sharedPref = getSharedPreferences("mypref", 0);
       String name = sharedPref.getString("name", "");

       if (name.equalsIgnoreCase("required_Text")) {
          Log.v("Matched","Required Text Matched");
          } else {
               Log.v("Not Matched","Required Text Not Matched"); 
                 }
 0
Author: Nadeem Abbas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-01 16:09:28

Wspólne Preferencje są tak łatwe do nauczenia się, więc spójrz na to prosty tutorial o sharedpreference

import android.os.Bundle;
import android.preference.PreferenceActivity;

    public class UserSettingActivity extends PreferenceActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

      addPreferencesFromResource(R.xml.settings);

    }
}
 0
Author: dondondon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-10 15:24:56