简体   繁体   English

android SharedPreferences 和 Map

[英]android SharedPreferences and Map

In my app I save some user information (ie name, weight, height) as key-value-pairs using SharedPreferences.在我的应用程序中,我使用 SharedPreferences 将一些用户信息(即姓名、体重、身高)保存为键值对。

These information are used in several activities.这些信息用于多项活动。 So I thought, instead of implementing the whole procedure for reading/writing to the SharedPreferences in each activity, I also could implement a class "UserData" and define several static methods.所以我想,除了在每个活动中实现读取/写入 SharedPreferences 的整个过程之外,我还可以实现一个“UserData”类并定义几个静态方法。 So when I need some user information or want to save them I only use methods of the class "UserData" and this class handles all the stuff in background.所以当我需要一些用户信息或想要保存它们时,我只使用“UserData”类的方法,这个类在后台处理所有的东西。

So I did the following things:所以我做了以下几件事:

  • class UserData contains a private Map<String,?>UserData包含一个私有Map<String,?>
  • this map is filled by the getAll() -Method of SharedPreferences该地图由SharedPreferencesgetAll()方法填充
  • initialization is triggerd in the onCreate() -Method in each activity初始化在每个活动的onCreate() -Method 中触发
  • providing the values (for each possible type) to a defined key is done by the getValue(String key) -Method为定义的键提供值(对于每种可能的类型)由getValue(String key) -Method 完成
  • writing (new) information should be done by setter methods写入(新)信息应该由 setter 方法完成
  • to write back to shared preferences, there is a save function写回共享首选项,有一个保存功能

But now I have a lot of questions:但是现在我有很多问题:

  1. getAll() method I expect, that getAll() will read all key-value-pairs from the SharedPreferences.我期望getAll()方法, getAll()将从 SharedPreferences 读取所有键值对。 So I would expect, that after initialization data will contain (String,String)-pairs (ie "name";"Max") as well as (String,Integer)-pairs (ie "weight",85).所以我希望,初始化后的data将包含 (String,String)-pairs (ie "name";"Max") 以及 (String,Integer)-pairs (ie "weight",85)。 Am I right?我对吗?

  2. getting the values Is the way, how I return the values in getValue(String key) correct?获取值是这样,我如何返回getValue(String key)的值是否正确? How can I get the value type from such a Map<String,?> or Map.Entry<String,?> definition?如何从这样的Map<String,?>Map.Entry<String,?>定义中获取值类型?

  3. adding Entries to the map I have no idea how to overwrite or write new entries to data .将条目添加到地图我不知道如何覆盖或写入新条目到data One Idea was, to create a set-method for each type (ie String, Integer) I can save in SharedPreferences, create an Entry within this method and then calling an add-method.一个想法是,为我可以保存在 SharedPreferences 中的每种类型(即字符串、整数)创建一个设置方法,在此方法中创建一个条目,然后调用一个添加方法。 But how should this looks like?但这应该是怎样的呢?

  4. saving Will this saving fuction work properly?保存 这个保存功能会正常工作吗? I'm not realy sure.我不太确定。

Or is this a total stupid approach?或者这是一个完全愚蠢的方法? Thanks for your support.谢谢您的支持。

This is my UserData-class这是我的 UserData 类

public class UserData {

    static private boolean isInit = false;

    static private Map<String,?> data = new HashMap<>();

    static void initialize(Context context){
        if(UserData.isInit){
            return;
        }
        if(context==null){
            return;
        }

        // read data from memory
        SharedPreferences pref = context.getSharedPreferences(context.getString(R.string.app_userdata),Context.MODE_PRIVATE);
        UserData.data = pref.getAll();
        Log.v(TAG,"loaded " + UserData.data.size() +" key-value-pairs into map");
        UserData.isInit=true;
    }

    static void reinitialize(Context context){
        UserData.isInit=false;
        UserData.initialize(context);
    }

    static <T> T getValue(String key){
        Object value = UserData.data.get(key);
        if(value instanceof T){
            return (T)value;
        }else{
            return null;
        }
    }

    static <T> T getValue(String key,T retErr){
        T value = getValue(key);
        if(value!=null){
            return value;
        }else{
            return retErr;
        }
    }

    static void setString(String key, String str){

    }

    static void setInteger(String key, Integer i){

    }

    static private void addElement(Map.Entry<String,?> element){
    }

    static void save(Context context){
        SharedPreferences pref = context.getSharedPreferences(context.getString(R.string.app_userdata),Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();

       for(Map.Entry<String,?> pair : UserData.data.entrySet()){
           Object value = pair.getValue();
           if(value instanceof String){
               editor.putString(pair.getKey(),value.toString());
           }else if(value instanceof Integer){
               editor.putInt(pair.getKey(),(Integer)value);
           }else if(value instanceof Float){
               editor.putFloat(pair.getKey(),(Float) value);
           }else if(value instanceof Boolean){
               editor.putBoolean(pair.getKey(),(Boolean) value);
           }
       }
        editor.apply();
    }
}

Sample Activity示例活动

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        UserData.initialize(getApplicationContext());
    }
}

i think you are trying to recreate the wheel.我认为您正在尝试重新创建轮子。 if you want to create a custom class for saving, adding, or even editing shared pref, that fine.如果你想创建一个自定义类来保存、添加甚至编辑共享首选项,那很好。 Shared pref is a map, for you to use another map, just seems backwards to me.共享首选项一张地图,让你使用另一张地图,对我来说似乎是倒退。

SharedPreferences pref = getApplicationContext().getSharedPreferences("sharedPreferences", 0); // 0 - for private mode

Storing data into Shared pref.将数据存储到共享首选项中。

Editor editor = pref.edit();
editor.putBoolean("name", "bill");
editor.commit();

To get the name获取名称

String name = pref.getString("name", null); //value is null if the key 'name' doesnt exist. you can also put in any string value here

remove data from shared pref从共享首选项中删除数据

editor.remove("name");
editor.commit();

to remove everything..删除一切..

editor.clear();
editor.commit();

If you want to create a class that does this, thats fine, but dont add the data into a map.如果您想创建一个执行此操作的类,那很好,但不要将数据添加到地图中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM