2013-01-24 17 views
8

Chciałbym przechowywać obiekt klasy w Androidzie sharedpreference. Zrobiłem kilka podstawowych wyszukiwań i otrzymałem odpowiedzi, takie jak uczynienie tego obiektu serializowalnym i zapisanie go, ale moja potrzeba jest tak prosta. Chciałbym przechowywać pewne informacje o użytkowniku, takie jak nazwa, adres, wiek i wartość boolowska są aktywne. Zrobiłem dla tego jedną klasę użytkownika.Jak przechowywać obiekt klasy w Androidzie 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; 
    } 
} 

Dzięki.

+0

Dlaczego nie można go przekształcić do postaci szeregowej? To poprawne rozwiązanie. – Simon

Odpowiedz

18
  1. Pobierz gson-1.7.1.jar z tego linku: GsonLibJar

  2. Dodaj tę bibliotekę do android projektu i skonfigurować Build Path.

  3. Dodaj następującą klasę do swojego pakietu.

    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. Utwórz jeszcze jedną klasę, rozszerzając Application klasy jak ten

    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. Dodaj tę klasę aplikacji w Twojej manifestu application tagu takiego.

    <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. na głównej działalności, w których chciałeś przechowywania wartości w Shared Preference zrobić coś takiego.

    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. W innej działalności, gdzie chciał, aby uzyskać wartość od Preference zrobić coś takiego.

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

Nadzieja to może pomóc. W tej odpowiedzi użyłem twojej klasy dla odniesienia "Użytkownik", abyś mógł lepiej zrozumieć. Nie możemy jednak przekazywać tej metody, jeśli zdecydujesz się przechowywać bardzo duże obiekty w preferencji, ponieważ wszyscy wiemy, że mamy ograniczony rozmiar pamięci dla każdej aplikacji w katalogu danych, więc jeśli masz pewność, że masz tylko ograniczone dane do przechowywania we współdzielonej preferencji możesz użyć tej alternatywy.

Wszelkie sugestie dotyczące tego narzędzia są mile widziane.

+0

Jak mogę uzyskać listę tablic jako obiekt, jeśli zapisuję go jako listę znaków typu przy użyciu tego –

+1

@PankajNimgade Możesz ustawić swój arrayList na obiekt, ale upewnij się, że możesz serializować obiekt zawiera w tablicyList. Co więcej, możesz zrobić parcelę i bezpośrednio przekazać ją do zamierzonego celu. –

+0

Dziękuję bardzo :) –

1

Innym sposobem jest, aby zapisać każdą nieruchomość przez itself..Preferences przyjmować tylko prymitywne typy, więc nie można umieścić złożonego obiektu w nim

0

może po prostu dodać kilka normalnych SharedPreferences „nazwa”, „adres ”,«wiek»&«isActive»i po prostu załadować je przy uruchamianiu klasę

0

można użyć globalnej klasy

public class GlobalState extends Application 
     { 
    private String testMe; 

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

a następnie znajdź swój tag aplikacji w nadroid menifest i dodać to do niego:

Można ustawić i pobrać dane z dowolnej aktywności za pomocą następującego kodu.

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

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

Proste rozwiązanie tego, jak przechowywać wartość logowania w SharedPreferences.

Możesz rozszerzyć klasę MainActivity lub inną klasę, w której będziesz przechowywać "wartość czegoś, co chcesz zachować". Połóż to w klasie pisarzy i czytników:

public static final String GAME_PREFERENCES_LOGIN = "Login"; 

Tutaj InputClass to wejście, a OutputClass to odpowiednio klasa wyjściowa.

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

Teraz można go używać gdzie indziej, jak inne klasy. Poniżej znajduje się 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); 
Powiązane problemy