598 Stimmen

Wie man SharedPreferences in Android zum Speichern, Abrufen und Bearbeiten von Werten verwendet

Ich möchte einen Zeitwert speichern und muss ihn abrufen und bearbeiten. Wie kann ich SharedPreferences um dies zu tun?

0 Stimmen

Ich habe einen Generic SharedPreferences Wrapper implementiert, schauen Sie mal rein: Android-know-how-to.blogspot.co.il/2014/03/

0 Stimmen

A vereinfachter Ansatz wäre durch die Verwendung dieser Bibliothek: github.com/viralypatel/Android-SharedPreferences-Helper ... erweiterte technische Details in meinem hier antworten ...

0 Stimmen

29voto

ArcDare Punkte 3046

Das ist der einfachste Weg:

Zum Sparen:

getPreferences(MODE_PRIVATE).edit().putString("Name of variable",value).commit();

Zum Abrufen:

your_variable = getPreferences(MODE_PRIVATE).getString("Name of variable",default value);

19voto

Jorgesys Punkte 119076

Einstellung von Werten in Präferenz:

// 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.commit();

Abrufen von Daten aus der Präferenz:

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
  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.
}

Mehr Informationen:

Gemeinsame Präferenzen verwenden

Gemeinsame Präferenzen

18voto

fidazik Punkte 405

Zum Speichern von Informationen

SharedPreferences preferences = getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("username", username.getText().toString());
editor.putString("password", password.getText().toString());
editor.putString("logged", "logged");
editor.commit();

So setzen Sie Ihre Einstellungen zurück

SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();

14voto

alexm Punkte 1237

Wenn Sie eine große Anwendung mit anderen Entwicklern in Ihrem Team erstellen und alles gut organisiert haben wollen, ohne verstreuten Code oder verschiedene SharedPreferences-Instanzen, können Sie so vorgehen:

//SharedPreferences manager class
public class SharedPrefs {

    //SharedPreferences file name
    private static String SHARED_PREFS_FILE_NAME = "my_app_shared_prefs";

    //here you can centralize all your shared prefs keys
    public static String KEY_MY_SHARED_BOOLEAN = "my_shared_boolean";
    public static String KEY_MY_SHARED_FOO = "my_shared_foo";

    //get the SharedPreferences object instance
    //create SharedPreferences file if not present

    private static SharedPreferences getPrefs(Context context) {
        return context.getSharedPreferences(SHARED_PREFS_FILE_NAME, Context.MODE_PRIVATE);
    }

    //Save Booleans
    public static void savePref(Context context, String key, boolean value) {
        getPrefs(context).edit().putBoolean(key, value).commit();       
    }

    //Get Booleans
    public static boolean getBoolean(Context context, String key) {
        return getPrefs(context).getBoolean(key, false);
    }

    //Get Booleans if not found return a predefined default value
    public static boolean getBoolean(Context context, String key, boolean defaultValue) {
        return getPrefs(context).getBoolean(key, defaultValue);
    }

    //Strings
    public static void save(Context context, String key, String value) {
        getPrefs(context).edit().putString(key, value).commit();
    }

    public static String getString(Context context, String key) {
        return getPrefs(context).getString(key, "");
    }

    public static String getString(Context context, String key, String defaultValue) {
        return getPrefs(context).getString(key, defaultValue);
    }

    //Integers
    public static void save(Context context, String key, int value) {
        getPrefs(context).edit().putInt(key, value).commit();
    }

    public static int getInt(Context context, String key) {
        return getPrefs(context).getInt(key, 0);
    }

    public static int getInt(Context context, String key, int defaultValue) {
        return getPrefs(context).getInt(key, defaultValue);
    }

    //Floats
    public static void save(Context context, String key, float value) {
        getPrefs(context).edit().putFloat(key, value).commit();
    }

    public static float getFloat(Context context, String key) {
        return getPrefs(context).getFloat(key, 0);
    }

    public static float getFloat(Context context, String key, float defaultValue) {
        return getPrefs(context).getFloat(key, defaultValue);
    }

    //Longs
    public static void save(Context context, String key, long value) {
        getPrefs(context).edit().putLong(key, value).commit();
    }

    public static long getLong(Context context, String key) {
        return getPrefs(context).getLong(key, 0);
    }

    public static long getLong(Context context, String key, long defaultValue) {
        return getPrefs(context).getLong(key, defaultValue);
    }

    //StringSets
    public static void save(Context context, String key, Set<String> value) {
        getPrefs(context).edit().putStringSet(key, value).commit();
    }

    public static Set<String> getStringSet(Context context, String key) {
        return getPrefs(context).getStringSet(key, null);
    }

    public static Set<String> getStringSet(Context context, String key, Set<String> defaultValue) {
        return getPrefs(context).getStringSet(key, defaultValue);
    }
}

In Ihrer Aktivität können Sie SharedPreferences folgendermaßen speichern

//saving a boolean into prefs
SharedPrefs.savePref(this, SharedPrefs.KEY_MY_SHARED_BOOLEAN, booleanVar);

und Sie können Ihre SharedPreferences folgendermaßen abrufen

//getting a boolean from prefs
booleanVar = SharedPrefs.getBoolean(this, SharedPrefs.KEY_MY_SHARED_BOOLEAN);

12voto

Sathish Punkte 2173

In jeder Anwendung gibt es Standardeinstellungen, auf die man über die Schaltfläche PreferenceManager Instanz und die zugehörige Methode getDefaultSharedPreferences(Context) .

Mit dem SharedPreference Instanz kann man den int-Wert einer beliebigen Präferenz mit dem Befehl getInt(String key, int defVal) . Die Präferenz, die uns in diesem Fall interessiert, ist der Zähler.

In unserem Fall können wir die SharedPreference Instanz, in unserem Fall mit der Funktion edit(), und verwenden Sie die putInt(String key, int newVal) Wir haben die Anzahl der Bewerbungen, die über die Bewerbung hinaus bestehen, erhöht und entsprechend angezeigt.

Zur weiteren Veranschaulichung starten Sie die Anwendung erneut. Sie werden feststellen, dass die Anzahl bei jedem Neustart der Anwendung steigt.

VoreinstellungenDemo.java

コード

package org.example.preferences;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.TextView;

public class PreferencesDemo extends Activity {
   /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Get the app's shared preferences
        SharedPreferences app_preferences = 
        PreferenceManager.getDefaultSharedPreferences(this);

        // Get the value for the run counter
        int counter = app_preferences.getInt("counter", 0);

        // Update the TextView
        TextView text = (TextView) findViewById(R.id.text);
        text.setText("This app has been started " + counter + " times.");

        // Increment the counter
        SharedPreferences.Editor editor = app_preferences.edit();
        editor.putInt("counter", ++counter);
        editor.commit(); // Very important
    }
}

main.xml

コード

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:orientation="vertical"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent" >

        <TextView
            android:id="@+id/text"  
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content" 
            android:text="@string/hello" />
</LinearLayout>

CodeJaeger.com

CodeJaeger ist eine Gemeinschaft für Programmierer, die täglich Hilfe erhalten..
Wir haben viele Inhalte, und Sie können auch Ihre eigenen Fragen stellen oder die Fragen anderer Leute lösen.

Powered by:

X