2013-01-24 12 views
8

Vorrei memorizzare l'oggetto di classe in android sharedpreference. Ho fatto alcune ricerche di base su questo e ho ottenuto alcune risposte come renderlo oggetto serializzabile e memorizzarlo, ma il mio bisogno è così semplice. Vorrei memorizzare alcune informazioni utente come nome, indirizzo, età e valore booleano attivo. Ho creato una classe utente per questo.Come archiviare l'oggetto classe in android sharedPreference?

public class User { 
    private String name; 
    private String address; 
    private int  age; 
    private boolean isActive; 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    public String getAddress() { 
     return address; 
    } 

    public void setAddress(String address) { 
     this.address = address; 
    } 

    public int getAge() { 
     return age; 
    } 

    public void setAge(int age) { 
     this.age = age; 
    } 

    public boolean isActive() { 
     return isActive; 
    } 

    public void setActive(boolean isActive) { 
     this.isActive = isActive; 
    } 
} 

Grazie.

+0

Perché non renderlo serializzabile? È la soluzione corretta – Simon

risposta

18
  1. Scarica gson-1.7.1.jar da questo link: GsonLibJar

  2. Aggiungi questa libreria al progetto Android e configurare percorso di generazione.

  3. Aggiungere la seguente classe al pacchetto.

    package com.abhan.objectinpreference; 
    
    import java.lang.reflect.Type; 
    import android.content.Context; 
    import android.content.SharedPreferences; 
    import com.google.gson.Gson; 
    import com.google.gson.reflect.TypeToken; 
    
    public class ComplexPreferences { 
        private static ComplexPreferences  complexPreferences; 
        private final Context     context; 
        private final SharedPreferences   preferences; 
        private final SharedPreferences.Editor editor; 
        private static Gson      GSON   = new Gson(); 
        Type         typeOfObject = new TypeToken<Object>(){} 
                       .getType(); 
    
    private ComplexPreferences(Context context, String namePreferences, int mode) { 
        this.context = context; 
        if (namePreferences == null || namePreferences.equals("")) { 
         namePreferences = "abhan"; 
        } 
        preferences = context.getSharedPreferences(namePreferences, mode); 
        editor = preferences.edit(); 
    } 
    
    public static ComplexPreferences getComplexPreferences(Context context, 
         String namePreferences, int mode) { 
        if (complexPreferences == null) { 
         complexPreferences = new ComplexPreferences(context, 
           namePreferences, mode); 
        } 
        return complexPreferences; 
    } 
    
    public void putObject(String key, Object object) { 
        if (object == null) { 
         throw new IllegalArgumentException("Object is null"); 
        } 
        if (key.equals("") || key == null) { 
         throw new IllegalArgumentException("Key is empty or null"); 
        } 
        editor.putString(key, GSON.toJson(object)); 
    } 
    
    public void commit() { 
        editor.commit(); 
    } 
    
    public <T> T getObject(String key, Class<T> a) { 
        String gson = preferences.getString(key, null); 
        if (gson == null) { 
         return null; 
        } 
        else { 
         try { 
          return GSON.fromJson(gson, a); 
         } 
         catch (Exception e) { 
          throw new IllegalArgumentException("Object stored with key " 
            + key + " is instance of other class"); 
         } 
        } 
    } } 
    
  4. Creare una classe più estendendo Application classe come questa

    package com.abhan.objectinpreference; 
    
    import android.app.Application; 
    
    public class ObjectPreference extends Application { 
        private static final String TAG = "ObjectPreference"; 
        private ComplexPreferences complexPrefenreces = null; 
    
    @Override 
    public void onCreate() { 
        super.onCreate(); 
        complexPrefenreces = ComplexPreferences.getComplexPreferences(getBaseContext(), "abhan", MODE_PRIVATE); 
        android.util.Log.i(TAG, "Preference Created."); 
    } 
    
    public ComplexPreferences getComplexPreference() { 
        if(complexPrefenreces != null) { 
         return complexPrefenreces; 
        } 
        return null; 
    } } 
    
  5. Aggiungi che classe di applicazione in application tag del manifesto come questo.

    <application android:name=".ObjectPreference" 
        android:allowBackup="false" 
        android:icon="@drawable/ic_launcher" 
        android:label="@string/app_name" 
        android:theme="@style/AppTheme" > 
    ....your activities and the rest goes here 
    </application> 
    
  6. nella vostra attività principale dove si voleva per memorizzare il valore in Shared Preference fare qualcosa di simile.

    package com.abhan.objectinpreference; 
    
    import android.app.Activity; 
    import android.content.Intent; 
    import android.os.Bundle; 
    import android.view.View; 
    
    public class MainActivity extends Activity { 
        private final String TAG = "MainActivity"; 
        private ObjectPreference objectPreference; 
    
        @Override 
        protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_main); 
    
        objectPreference = (ObjectPreference) this.getApplication(); 
    
        User user = new User(); 
        user.setName("abhan"); 
        user.setAddress("Mumbai"); 
        user.setAge(25); 
        user.setActive(true); 
    
        User user1 = new User(); 
        user1.setName("Harry"); 
        user.setAddress("London"); 
        user1.setAge(21); 
        user1.setActive(false); 
    
        ComplexPreferences complexPrefenreces = objectPreference.getComplexPreference(); 
        if(complexPrefenreces != null) { 
         complexPrefenreces.putObject("user", user); 
         complexPrefenreces.putObject("user1", user1); 
         complexPrefenreces.commit(); 
        } else { 
         android.util.Log.e(TAG, "Preference is null"); 
        } 
    } 
    
    } 
    
  7. In un'altra attività in cui si voleva ottenere il valore dal Preference fare qualcosa di simile.

    package com.abhan.objectinpreference; 
    
    import android.app.Activity; 
    import android.os.Bundle; 
    
    public class SecondActivity extends Activity { 
        private final String TAG = "SecondActivity"; 
        private ObjectPreference objectPreference; 
    
        @Override 
        protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_second); 
    
        objectPreference = (ObjectPreference) this.getApplication(); 
        ComplexPreferences complexPreferences = objectPreference.getComplexPreference(); 
    
        android.util.Log.i(TAG, "User"); 
        User user = complexPreferences.getObject("user", User.class); 
        android.util.Log.i(TAG, "Name " + user.getName()); 
        android.util.Log.i(TAG, "Address " + user.getAddress()); 
        android.util.Log.i(TAG, "Age " + user.getAge()); 
        android.util.Log.i(TAG, "isActive " + user.isActive()); 
        android.util.Log.i(TAG, "User1"); 
        User user1 = complexPreferences.getObject("user", User.class); 
        android.util.Log.i(TAG, "Name " + user1.getName()); 
        android.util.Log.i(TAG, "Address " + user1.getAddress()); 
        android.util.Log.i(TAG, "Age " + user1.getAge()); 
        android.util.Log.i(TAG, "isActive " + user1.isActive()); 
    } } 
    

Spero che questo ti può aiutare. In questa risposta ho usato la tua classe per il riferimento "Utente" in modo da poter capire meglio. Tuttavia, non è possibile inoltrare questo metodo se si è scelto di archiviare oggetti molto grandi di preferenza poiché tutti sappiamo che abbiamo una dimensione di memoria limitata per ogni app nella directory dei dati, in modo tale che, se si è sicuri di disporre solo di dati limitati da memorizzare nelle preferenze condivise puoi usare questa alternativa

Eventuali suggerimenti su questo strumento sono i benvenuti.

+0

Come posso ottenere un arraylist come oggetto se lo sto salvando come Arrayist di un tipo usando questo –

+1

@PankajNimgade Puoi impostare il tuo arrayList su un oggetto ma assicurati di poter serializzare il tuo oggetto contenuto in arrayList. Inoltre, puoi renderlo parcelable e passarlo direttamente all'intento. –

+0

Grazie mille :) –

1

l'altro modo è quello di salvare ciascuna struttura itself..Preferences accettano solo tipi primitivi, quindi non si può mettere un oggetto complesso in esso

0

Si può solo aggiungere alcuni SharedPreferences normali indirizzo "nome"," ", 'età' & 'isActive' e semplicemente caricare quando un'istanza della classe

0

è possibile utilizzare la classe globale

public class GlobalState extends Application 
     { 
    private String testMe; 

    public String getTestMe() { 
     return testMe; 
     } 
    public void setTestMe(String testMe) { 
    this.testMe = testMe; 
    } 
} 

e quindi individuare il tag applicazione in menifest nadroid, e aggiungere questo in esso:

android:name="com.package.classname" 

ed è possibile impostare e ottenere i dati da qualsiasi attività utilizzando il seguente codice.

 GlobalState gs = (GlobalState) getApplication(); 
    gs.setTestMe("Some String");</code> 

     // Get values 
    GlobalState gs = (GlobalState) getApplication(); 
    String s = gs.getTestMe();  
0

Soluzione semplice di come memorizzare il valore di accesso in SharedPreferences.

È possibile estendere la classe MainActivity o un'altra classe in cui verrà archiviato il "valore di qualcosa che si desidera conservare". Metti questo nelle classi di scrittore e lettore:

public static final String GAME_PREFERENCES_LOGIN = "Login"; 

Qui InputClass è input e OutputClass è classe di uscita, rispettivamente.

// This is a storage, put this in a class which you can extend or in both classes: 
//(input and output) 
public static final String GAME_PREFERENCES_LOGIN = "Login"; 

// String from the text input (can be from anywhere) 
String login = inputLogin.getText().toString(); 

// then to add a value in InputCalss "SAVE", 
SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0); 
Editor editor = example.edit(); 
editor.putString("value", login); 
editor.commit(); 

Ora puoi usarlo da qualche altra parte, come l'altra classe. Quello che segue è OutputClass.

SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0); 
String userString = example.getString("value", "defValue"); 

// the following will print it out in console 
Logger.getLogger("Name of a OutputClass".class.getName()).log(Level.INFO, userString); 
Problemi correlati