Seit API Level 1, also seit den Anfängen von Android, gibt es in Android eine API zum Speichern von Schlüssel-Wert-Paaren. Wenn Sie neu in Android sind oder lernen wollen, wie man SharedPreferences verwendet, sollten Sie diese API nutzen.

In diesem Tutorial werden wir verschiedene Beispiele für die Verwendung von Sharedpreferences zum Speichern und Abrufen von Daten betrachten. Meistens werden wir primitive dtaa-Typen in unseren sharedpreferences speichern.

Beispiel 1: Kotlin Android - SharedPreferences Beispiel

Dies ist ein einfaches Beispiel für SharedPreferences, geschrieben in Kotlin.

Demo

Hier ist die Demo dessen, was erstellt wird:

Kotlin Android Shared Preferences Example

Schritt 1: Abhängigkeiten

Es sind keine speziellen Abhängigkeiten oder Abhängigkeiten von Drittanbietern notwendig.

Schritt 2: Layout entwerfen

Entwerfen Sie Ihr xml-Layout wie folgt:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:padding="10dp"
        android:textColor="#101010"
        android:textSize="25sp"/>

    <EditText
        android:id="@+id/edt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/enter_a_text"
        android:layout_margin="10dp"
        android:textColor="#101010"/>

    <Button
        android:id="@+id/save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/save"
        android:layout_margin="10dp"/>

    <Button
        android:id="@+id/show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/show"
        android:layout_margin="10dp"/>

</LinearLayout>

Schritt 3: Code schreiben

Schreiben Sie dann Ihren Kotlin-Code wie folgt:

MainActivity.kt

Hier ist der vollständige Code für die Hauptaktivität:

package arb.test.shared.perferences

import android.content.Context
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    lateinit var shared : SharedPreferences

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        shared = getSharedPreferences("Test" , Context.MODE_PRIVATE)

        save.setOnClickListener {

            val edit = shared.edit()
            edit.putString("txt" , edt.text.toString())
            Toast.makeText(this , "Was Saved" , Toast.LENGTH_SHORT).show()
            edit.apply()
        }

        show.setOnClickListener {

            txt.text = shared.getString("txt" , "No imported" )
            Toast.makeText(this ,  shared.getString("txt" , "No imported" ) , Toast.LENGTH_SHORT).show()
        }

    }
}

Run

Führen Sie das Projekt aus.

References

Hier sind die Download-Links:

Dowload Code
Durchsuchen Code

Beispiel 2: Sitzungsverwaltung mit SharedPreferences

In diesem Beispiel lernen Sie, wie man mit SharedPreferences Benutzersitzungen verwaltet, z.B. nachdem sich ein Benutzer bei der App angemeldet hat. Dieses Beispiel ist ebenfalls in Kotlin geschrieben.

Es enthält diese drei Dateien:

  1. Zwei Aktivitäten - Erste und Anmeldeaktivitäten.
  2. Sesson Manager - SharedPreferences Klasse

Fangen wir an.

Schritt 1: Projekt erstellen

Beginnen Sie mit der Erstellung eines leeren Android Studio-Projekts.

Schritt 2: Abhängigkeiten

Für dieses Projekt werden keine externen Abhängigkeiten benötigt.

Schritt 3: Layouts entwerfen.

Wir werden zwei Layouts entwerfen:

(a). activity_login.xml

Dies ist die Login-Aktivität. Fügen Sie zwei TextViews und einen Button hinzu:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    tools:context=".LoginActivity">

    <TextView
        android:id="@+id/Disp_Username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="Username"
        android:textColor="@color/colorPrimary"/>

    <TextView
        android:id="@+id/Disp_Password"
        android:layout_marginTop="20dp"
        android:textColor="@color/colorPrimary"
        android:textSize="20sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Password"/>

    <Button
        android:id="@+id/btnLogout"
        android:layout_marginTop="40dp"
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:layout_marginEnd="40dp"
        android:layout_marginStart="40dp"
        android:background="@color/colorPrimary"
        android:textColor="@android:color/white"
        android:text="Logout"/>

</LinearLayout>

(b). activity_first.xml

Dies ist das Layout für die Hauptaktivität. Fügen Sie einen Button und zwei Edittexte hinzu:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".FirstActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Session Management"
        android:textColor="@color/colorPrimary"
        android:textSize="30sp"/>

    <EditText
        android:id="@+id/txtUsername"
        android:layout_marginTop="50dp"
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:textColorHint="@color/colorPrimary"
        android:textColor="@color/colorPrimary"
        android:layout_marginEnd="40dp"
        android:layout_marginStart="40dp"
        android:background="@null"
        android:hint="Username"/>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginEnd="40dp"
        android:layout_marginStart="40dp"
        android:background="@color/colorPrimary"/>

    <EditText
        android:id="@+id/txtPassword"
        android:layout_marginTop="20dp"
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:textColorHint="@color/colorPrimary"
        android:textColor="@color/colorPrimary"
        android:layout_marginEnd="40dp"
        android:layout_marginStart="40dp"
        android:background="@null"
        android:hint="Password"/>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginEnd="40dp"
        android:layout_marginStart="40dp"
        android:background="@color/colorPrimary"/>

    <Button
        android:id="@+id/btnLogin"
        android:layout_marginTop="20dp"
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:layout_marginEnd="40dp"
        android:layout_marginStart="40dp"
        android:text="Login"
        android:textColor="@android:color/white"
        android:background="@color/colorPrimary"/>

</LinearLayout>

Schritt 4: Sitzungsmanager erstellen

Erstellen Sie den Sitzungsmanager mit Hilfe von sharedpreferences. Erstellen Sie zunächst die Datei SessionManager.kt mit den folgenden Instanzfeldern: ein SharedPreferences-Objekt, ein SharedPreferences.Editor-Objekt, ein Context-Objekt und eine Ganzzahl zur Darstellung des privaten Modus:

class SessionManager {

    var pref: SharedPreferences
    var edior: SharedPreferences.Editor
    var context: Context
    var PRIVATE_MODE: Int = 0

Initialisieren Sie sie im Konstruktor:

    constructor(context: Context) {

        this.context = context
        pref = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE)
        edior = pref.edit()
    }

Definieren Sie statische Felder in einem Begleitobjekt:

    companion object {

        val PREF_NAME: String = "KotlinDemo"
        val IS_LOGIN: String = "isLogin"
        val KEY_NAME: String = "name"
        val KEY_PASS: String = "pass"

    }

So erstellen Sie eine Anmeldesitzung:

    fun createLoginSession(name: String, emai: String) {

        edior.putBoolean(IS_LOGIN, true)
        edior.putString(KEY_NAME, name)
        edior.putString(KEY_PASS, emai)
        edior.commit()
    }

So überprüfen Sie die Anmeldung:

    fun checkLogin() {

        if (!this.isLoggedIn()) {
            var i: Intent = Intent(context, FirstActivity::class.java)
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
            context.startActivity(i)
        }
    }

So holt man sich die Benutzerdaten aus den sharedpreferences und gibt sie in einer HashMap zurück:

    fun getUserDetails(): HashMap<String, String> {

        var user: Map<String, String> = HashMap<String, String>()
        (user as HashMap).put(KEY_NAME, pref.getString(KEY_NAME, null).toString())
        (user as HashMap).put(KEY_PASS, pref.getString(KEY_PASS, null).toString())

        return user
    }

So wird ein Benutzer abgemeldet:

    fun LogoutUser() {
        edior.clear()
        edior.commit()

        val i: Intent = Intent(context, LoginActivity::class.java)
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
        context.startActivity(i)
    }

Und so prüft man, ob ein Benutzer angemeldet ist:


    fun isLoggedIn(): Boolean {

        return pref.getBoolean(IS_LOGIN, false)
    }

Hier ist der vollständige Code:

SessionManager.kt

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import com.example.sessionmanagementusingkotlin.FirstActivity
import com.example.sessionmanagementusingkotlin.LoginActivity

class SessionManager {

    var pref: SharedPreferences
    var edior: SharedPreferences.Editor
    var context: Context
    var PRIVATE_MODE: Int = 0

    constructor(context: Context) {

        this.context = context
        pref = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE)
        edior = pref.edit()
    }

    companion object {

        val PREF_NAME: String = "KotlinDemo"
        val IS_LOGIN: String = "isLogin"
        val KEY_NAME: String = "name"
        val KEY_PASS: String = "pass"

    }

    fun createLoginSession(name: String, emai: String) {

        edior.putBoolean(IS_LOGIN, true)
        edior.putString(KEY_NAME, name)
        edior.putString(KEY_PASS, emai)
        edior.commit()
    }

    fun checkLogin() {

        if (!this.isLoggedIn()) {
            var i: Intent = Intent(context, FirstActivity::class.java)
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
            context.startActivity(i)
        }
    }

    fun getUserDetails(): HashMap<String, String> {

        var user: Map<String, String> = HashMap<String, String>()
        (user as HashMap).put(KEY_NAME, pref.getString(KEY_NAME, null).toString())
        (user as HashMap).put(KEY_PASS, pref.getString(KEY_PASS, null).toString())

        return user
    }

    fun LogoutUser() {
        edior.clear()
        edior.commit()

        val i: Intent = Intent(context, LoginActivity::class.java)
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
        context.startActivity(i)
    }

    fun isLoggedIn(): Boolean {

        return pref.getBoolean(IS_LOGIN, false)
    }

}

Schritt 5: Aktivitäten erstellen

Wir haben zwei Aktivitäten:

(a). FirstActivity.kt

Wird einen Benutzer anmelden und seine/ihre Daten in SharedPreferences speichern:

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.sdnkcreations.sessionmanagerinkotlin.SessionManager
import kotlinx.android.synthetic.main.activity_first.*

class FirstActivity : AppCompatActivity() {

    lateinit var session: SessionManager

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_first)

        session = SessionManager(applicationContext)
        if (session.isLoggedIn()) {
            var i: Intent = Intent(applicationContext, FirstActivity::class.java)
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
            startActivity(i)
            finish()
        }

        btnLogin.setOnClickListener {

            val username: String = txtUsername.text.toString()
            val password: String = txtPassword.text.toString()

            if (username.trim().length > 0 && password.trim().length > 0) {

                session.createLoginSession(username, password)
                var i: Intent = Intent(applicationContext, LoginActivity::class.java)
                startActivity(i)
                finish()

            } else {

                Toast.makeText(this, "Login Failed...\n Please enter both credential", Toast.LENGTH_LONG).show()
            }

        }
    }
}

(b). LoginActivity.kt

Zeigt die Details eines eingeloggten Benutzers an:

class LoginActivity : AppCompatActivity() {

    lateinit var session: SessionManager

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        session = SessionManager(applicationContext)
        session.checkLogin()

        val user: HashMap<String, String> = session.getUserDetails()

        val name: String = user.get(SessionManager.KEY_NAME)!!
        val pass: String = user.get(SessionManager.KEY_PASS)!!

        Disp_Username.setText("Name: " + name)
        Disp_Password.setText("Email: " + pass)
        btnLogout.setOnClickListener {

            session.LogoutUser()
        }
    }
}

Ausführen

Kopieren Sie den Code oder laden Sie ihn über den unten stehenden Link herunter, bauen Sie ihn und führen Sie ihn aus.

Referenz

Hier sind die Referenzlinks:

Download Beispiel

SharedPreferences Schnipsel

In diesem Tutorial wollen wir uns SharedPreferences anschauen, was es ist, warum es wichtig ist und einige Beispiele.

Hier sind einige Beispiele für SharedPreferences.

import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.MainThread;

import com.jiangkang.tools.King;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;
import java.util.Set;

public class SpUtils {

    private SharedPreferences preferences;
    private static final String DEFAULT_PREF_NAME = "ktools_pref";
    private SharedPreferences.Editor editor;

    public static SpUtils getInstance(Context context,String name){
        return new SpUtils(context,name);
    }

    private SpUtils(Context context, String name) {
        preferences = context.getSharedPreferences(name,Context.MODE_PRIVATE);
        editor = preferences.edit();
    }

    public <T> SpUtils put(String key, T value){
        if (value instanceof String){
            editor.putString(key, (String) value);
        }else if (value instanceof Boolean){
            editor.putBoolean(key, (Boolean) value);
        }else if (value instanceof Integer){
            editor.putInt(key, (Integer) value);
        }else if (value instanceof Long){
            editor.putLong(key, (Long) value);
        }else if (value instanceof Float){
            editor.putFloat(key, (Float) value);
        }else {
            throw new IllegalArgumentException("value can not support");
        }
        return this;
    }

    public SpUtils putString(String key, String value){
        editor.putString(key,value).commit();
        return this;
    }

    public SpUtils putBoolean(String key, boolean value){
        editor.putBoolean(key, value).commit();
        return this;
    }

    public SpUtils putInt(String key, int value){
        editor.putInt(key,value).commit();
        return this;
    }

    public SpUtils putFloat(String key, float value){
        editor.putFloat(key, value).commit();
        return this;
    }

    public SpUtils putLong(String key, long value){
        editor.putLong(key, value).commit();
        return this;
    }

    public SpUtils putJsonObject(String key, JSONObject object){
        editor.putString(key,object.toString());
        return this;
    }

    public JSONObject getJsonObject(String key){
        String jsonString = preferences.getString(key,"{}");
        try {
            return new JSONObject(jsonString);
        } catch (JSONException e) {
            return null;
        }
    }

    public String getString(String key,String defaultValue){
        return preferences.getString(key,defaultValue);
    }

    public boolean getBoolean(String key, boolean defaultValue){
        return preferences.getBoolean(key, defaultValue);
    }

    public int getInt(String key, int defaultValue){
        return preferences.getInt(key, defaultValue);
    }

    public long getLong(String key, long defaultValue){
        return preferences.getLong(key, defaultValue);
    }

    public float getFloat(String key,float defaultValue){
        return preferences.getFloat(key, defaultValue);
    }

    public Map<String,?> getAll(){
        return preferences.getAll();
    }

}
2. Wie man JSON-Daten in SharedPreference speichert und abruft

Beginnen wir mit der Erstellung unserer Hauptanwendung.

Diese Klasse wird von der Klasse Application abgeleitet. Alles, was sie für uns tun wird, ist, den Anwendungskontext zu speichern und uns diesen zur Verfügung zu stellen.

import android.app.Application;
import android.content.Context;

public class MainApplication extends Application {

    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
    }

    public static Context getContext() {
        return context;
    }
}

Nachdem wir unsere Anwendungsklasse erstellt haben, können wir nun unsere json-Daten speichern und laden.

Die erste Methode ist die save() Methode. Sie erhält zwei Strings und ein Object.

Wir verwenden die Google Gson-Bibliothek. Es handelt sich um eine Bibliothek eines Drittanbieters, die als Abhängigkeit in der Datei build.gradle auf App-Ebene hinzugefügt werden muss.

Gehen Sie also zu Ihrer build.gradle-Datei (die sich im App-Ordner befindet) und fügen Sie die folgende Zeile unter der Dependencies-Schließung hinzu:

implementation 'com.google.code.gson:gson:2.8.1'

Vielleicht kannst du auch nach späteren Versionen suchen.

Sobald wir das Projekt synchronisiert haben, beginnen wir mit der Instanziierung unseres Gson;

        Gson gson = new Gson();

Dann holen wir unsere SharedPreferences:

        SharedPreferences pref = MainApplication.getContext().getSharedPreferences(identifier, Context.MODE_PRIVATE);

Dann erhalten wir ein SharedPreference.Editor Objekt, indem wir die edit() Methode unserer SharedPreferences Klasse aufrufen.

        SharedPreferences.Editor editor = pref.edit();

Dann konvertieren Sie unser Objekt mit der Methode toJson() der Klasse Gson in JSON. Dann fügen wir diese JSON-Daten neben dem Schlüssel zu unserer Instanz SharedPreference.Editor ein und rufen die Methode apply() auf:

        editor.putString(key, gson.toJson(object));
        editor.apply();

Auf diese Weise speichern wir die JSON-Daten in SharedPreferences.

Was ist mit dem Laden dieser Daten? Nun, wir können diese Daten auch einfach laden. Wiederum instanziieren Sie den Gson und initialisieren unsere SharedPreferences.

Dann erhalten wir unsere Daten als JSON-String, indem wir die Methode getString() der Klasse SharedPreferences aufrufen und dabei sicherstellen, dass wir den key übergeben:

        String json = pref.getString(key, null);

Wir prüfen, ob der Wert null ist, in diesem Fall geben wir null zurück. Andernfalls verwenden wir die Methode fromJson() der Klasse Gson, um unser Objekt zu erhalten.

Hier ist der Code:

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;
import com.slotnslot.slotnslot.MainApplication;

public class StorageUtil {
    public static void save(String identifier, String key, Object object) {
        Gson gson = new Gson();
        SharedPreferences pref = MainApplication.getContext().getSharedPreferences(identifier, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.putString(key, gson.toJson(object));
        editor.apply();
    }

    public static <T> T load(String identifier, String key, Class<T> clazz) {
        Gson gson = new Gson();
        SharedPreferences pref = MainApplication.getContext().getSharedPreferences(identifier, Context.MODE_PRIVATE);
        String json = pref.getString(key, null);
        return json == null ? null : gson.fromJson(json, clazz);
    }
}

Categorized in: