2013-01-24 11 views
8

私はandroid sharedpreferenceにクラスオブジェクトを格納したいと思います。私は基本的な検索を行いました。シリアル化可能なオブジェクトにして保存するような答えがありましたが、私の必要性はとても簡単です。私は名前、アドレス、年齢、ブール値のようないくつかのユーザー情報を保存したいと思います。私は1つのユーザークラスを作成しました。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; 
    } 
} 

ありがとうございます。

+0

なぜシリアル化できないのですか?それは正しい解決策です。 – Simon

答えて

18
  1. このリンクからダウンロードgson-1.7.1.jarGsonLibJar

  2. は、あなたのAndroidプロジェクトにこのライブラリを追加し、ビルド・パスを設定します。

  3. パッケージに次のクラスを追加します。

    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. このようなあなたのマニフェストのapplicationタグでそのアプリケーションのクラスを追加します。この

    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. ようApplicationクラスを拡張して1つの以上のクラスを作成します。あなたはこのような何かをShared Preferenceに格納する値に望んでいたあなたの主な活動で

    <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. 。あなたはこのような何かをPreferenceから値を取得したい別の活動で

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

これはあなたを助けることができると思います。この回答では、私はあなたのクラスを参考にして 'User'を使って、より理解しやすくなりました。ただし、データディレクトリ内の各アプリケーションのメモリサイズが制限されていることがわかっているため、非常に大きなオブジェクトを優先的に格納することを選択した場合、この方法ではリレーできません。この代替手段を使用することができます。

この実装に関する提案は大歓迎です。

+0

ArrayListをオブジェクトとして設定するにはどうすればいいですか? –

+1

@PankajNimgade arrayListをオブジェクトに設定できますが、arrayListに含まれるオブジェクトをシリアル化できることを確認してください。さらに、それを分割可能にして、それを意図に直接渡すこともできます。 –

+0

ありがとうありがとうございました:) –

1

他の方法はitself..Preferencesだけプリミティブ型を受け入れることにより、各プロパティを保存することですので、あなたは、あなただけのいくつかの正常SharedPreferencesを追加することができます

0

ことで、複雑なオブジェクトを置くことができない「名前」、「アドレス」、 『年齢』 & 『のisActive』とクラス

0

をインスタンス化する際に、単にあなたは

public class GlobalState extends Application 
     { 
    private String testMe; 

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

グローバルクラスを使用して、nadroid menifestでアプリケーションタグを見つけて、それにこれを追加することができ、それらをロードします。

android:name="com.package.classname" 

次のコードを使用して、任意のアクティビティからデータを設定して取得できます。

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

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

SharedPreferencesによってログイン値を格納する方法の簡単な解決法。

"保持したいものの値"を保存するMainActivityクラスまたは他のクラスを拡張することができます。これをwriterクラスとreaderクラスに入れます:

public static final String GAME_PREFERENCES_LOGIN = "Login"; 

ここで、InputClassは入力クラス、OutputClassは出力クラスクラスです。

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

他のクラスのように使用できます。以下は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); 
関連する問題