2013-01-24 25 views
8

Tôi muốn lưu trữ đối tượng lớp trong sharedpreference android. Tôi đã làm một số tìm kiếm cơ bản về điều đó và tôi đã nhận một số câu trả lời như làm cho nó serializable đối tượng và lưu trữ nó, nhưng nhu cầu của tôi là rất đơn giản. Tôi muốn lưu trữ một số thông tin người dùng như tên, địa chỉ, tuổi và giá trị boolean đang hoạt động. Tôi đã tạo một lớp người dùng cho điều đó.Làm thế nào để lưu trữ đối tượng lớp trong sharedPreference android?

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

Cảm ơn.

+0

Tại sao không làm cho nó có thể tuần tự? Đó là giải pháp đúng. – Simon

Trả lời

18
  1. Tải gson-1.7.1.jar từ liên kết này: GsonLibJar

  2. Thêm thư viện này cho dự án Android của bạn và cấu hình xây dựng con đường.

  3. Thêm lớp sau vào gói của bạn.

    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. Tạo một lớp hơn bằng cách mở rộng Application lớp như thế này

    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. Thêm vào đó lớp ứng dụng trong thẻ application của biểu hiện của bạn như thế này.

    <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. Trong Hoạt động chính của bạn, nơi bạn muốn giá trị lưu trữ trong Shared Preference làm điều gì đó như thế này.

    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. Trong hoạt động khác mà bạn muốn nhận giá trị từ Preference hãy làm như thế này.

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

Hy vọng điều này có thể giúp bạn. Trong câu trả lời này, tôi đã sử dụng lớp của bạn để tham khảo 'Người dùng' để bạn có thể hiểu rõ hơn. Tuy nhiên, chúng tôi không thể chuyển tiếp phương thức này nếu bạn chọn lưu trữ các đối tượng rất lớn theo sở thích vì chúng tôi đều biết rằng chúng tôi có kích thước bộ nhớ giới hạn cho mỗi ứng dụng trong thư mục dữ liệu sao cho bạn chắc chắn rằng bạn chỉ có dữ liệu giới hạn để lưu trữ trong tùy chọn được chia sẻ bạn có thể sử dụng phương án này.

Bất kỳ đề xuất nào về triển khai này đều được hoan nghênh nhất.

+0

làm thế nào tôi có thể nhận được một arraylist như một đối tượng nếu tôi tiết kiệm nó như Arraylist của một loại bằng cách sử dụng này –

+1

@PankajNimgade Bạn có thể đặt arrayList của bạn để đối tượng nhưng chắc chắn rằng bạn có thể serialize đối tượng của bạn có chứa trong arrayList. Hơn nữa, bạn có thể làm cho nó có thể chuyển nhượng và trực tiếp chuyển nó cho ý định. –

+0

Cảm ơn bạn rất nhiều :) –

1

cách khác là để tiết kiệm từng sở hữu bởi itself..Preferences chỉ chấp nhận các kiểu dữ liệu, vì vậy bạn không thể đặt một đối tượng phức tạp trong đó

0

Bạn chỉ có thể thêm một số SharedPreferences bình thường "tên", "địa chỉ ", 'tuổi' & 'IsActive' và chỉ cần tải chúng khi instantiating lớp

0

bạn có thể sử dụng lớp toàn cầu

public class GlobalState extends Application 
     { 
    private String testMe; 

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

và sau đó định vị trí thẻ ứng dụng của bạn trong menifest nadroid, và thêm vào đó:

android:name="com.package.classname" 

và bạn có thể đặt và nhận dữ liệu từ bất kỳ hoạt động nào của mình bằng cách sử dụng mã sau.

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

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

Giải pháp đơn giản về cách lưu trữ giá trị đăng nhập trong SharedPreferences.

Bạn có thể mở rộng lớp MainActivity hoặc lớp khác nơi bạn sẽ lưu trữ "giá trị của thứ bạn muốn giữ". Đặt thông tin này vào các lớp người viết và người đọc:

public static final String GAME_PREFERENCES_LOGIN = "Login"; 

Đây là InputClass là đầu vào và OutputClass là lớp đầu ra tương ứng.

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

Bây giờ bạn có thể sử dụng nó ở một nơi khác, như các lớp khác. Sau đây là 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); 
Các vấn đề liên quan