8

クラスオブジェクトをandroidsharedpreferenceに保存したいと思います。私はそれについていくつかの基本的な検索を行い、それをシリアル化可能なオブジェクトにして保存するなどのいくつかの答えを得ましたが、私の必要性はとても単純です。名前、住所、年齢、ブール値などのユーザー情報がアクティブになっていることを保存したいと思います。そのために1つのユーザークラスを作成しました。

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

ありがとう。

4

5 に答える 5

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

  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このようにクラスを拡張して、もう1つのクラスを作成します

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

    <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. 価値を保存したいメインアクティビティでは、Shared 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. あなたが価値を得たいと思った別の活動では、Preferenceこのようなことをしてください。

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

これがお役に立てば幸いです。この回答では、理解を深めるために、参照「ユーザー」にクラスを使用しました。ただし、非常に大きなオブジェクトを優先的に保存することを選択した場合、このメソッドを中継することはできません。データディレクトリ内の各アプリのメモリサイズが制限されているため、共有優先に保存するデータが限られていることが確実な場合は、この代替手段を使用できます。

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

于 2013-01-24T12:31:06.893 に答える
1

グローバルクラスを使用できます

    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();       
于 2013-01-24T12:24:24.560 に答える
1

もう1つの方法は、各プロパティを単独で保存することです。設定はプリミティブ型のみを受け入れるため、複雑なオブジェクトをその中に入れることはできません。

于 2013-01-24T12:18:40.183 に答える
0

通常のSharedPreferencesの「名前」、「アドレス」、「年齢」、「isActive」を追加して、クラスをインスタンス化するときにそれらをロードするだけです。

于 2013-01-24T12:20:18.890 に答える
0

SharedPreferencesによるログイン値の保存方法の簡単なソリューション。

MainActivityクラスまたは「保持したいものの値」を格納する他のクラスを拡張できます。これをライターとリーダーのクラスに入れます。

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);
于 2013-02-04T03:21:36.763 に答える