安卓快速入门系列2(sharedPreferences的应用)

shared Preference :当存储UI状态、用户首选项或者应用程序设置时,我们想要一种轻量级机制已存储一个已知的值集。Shared Preference使我们能够将一组原始数据的名称/值对保存为命名的首选项。

创建并保存Shared Preference

//创建或者得到一个SharedPreference
        SharedPreferences my=getSharedPreferences("mySharedPreference",Activity.MODE_PRIVATE);
        //使用sharedPreference的edit方法获得edit对象来修改值
        SharedPreferences.Editor editor=my.edit();
        //使用put<type>方法来插入或者更新与指定名称关联的值
        editor.putBoolean("boolean",true);
        editor.putFloat("float",1.1f);
        editor.putInt("int",1);
        editor.putLong("long",2L);
        editor.putString("string","我是字符串");
        Set<String> set=new HashSet<>();
        set.add("hello");
        set.add("world");
        editor.putStringSet("stringSet",set);
        //要保存编辑的动作,只需要调用edit对象的apply方法(异步方法,仅支持level9及其以上)或者commit方法(同步方法)即可
        //通常推荐使用apply方法
        editor.apply();

检索Shared Preference

//使用安全的get<type>方法来提取已经保存的值。每个get方法都接受一个键和一个默认值(如果取的键无值的情况使用)
        boolean isBoolean=my.getBoolean("boolean",false);
        float isFloat =my.getFloat("float",2.2f);
        int isInt=my.getInt("int",5);
        long isLong=my.getLong("long",10L);
        String isString=my.getString("string","我是字符串的默认值");
        Set<String> getSet=my.getStringSet("stringSet",new HashSet<>());
        //也可以使用getAll方法获得所有的键值对,遍历map就不在此解释了
        Map<String,?> map=my.getAll();
        //通过调用contains方法,可以检查特定的某个键值是否存在
        if (my.contains("world")){
            Log.i("exc","world这个键值对存在");
        }else {
            Log.i("exc","没有world这个键值对");
        }

使用SharedPreference的一个坑

今天搞了一段代码,存储临时数据,结果死活存不进去,我以为sharedPreferences.edit()的这个方法和hibernate的事务方法一样只有一个实例,结果是每次edit()都会创建一个新的edit,造成数据存储不上。

public void tts(View view) {
        sharedPreferences = getSharedPreferences("my", Context.MODE_PRIVATE);
        String s = ((EditText) findViewById(R.id.savett)).getText().toString();
        sharedPreferences.edit().putString("what", s);
        Toast.makeText(this, "存储了" + s, Toast.LENGTH_LONG).show();
        sharedPreferences.edit().commit();
    }

    public void show(View view) {
        sharedPreferences = getSharedPreferences("my", Context.MODE_PRIVATE);
        Toast.makeText(this, sharedPreferences.getString("what", null), Toast.LENGTH_LONG).show();
    }

修改后的代码

public void tts(View view) {
        sharedPreferences = getSharedPreferences("my", Context.MODE_PRIVATE);
        String s = ((EditText) findViewById(R.id.savett)).getText().toString();
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("what", s);
        Toast.makeText(this, "存储了" + s, Toast.LENGTH_LONG).show();
        editor.commit();
    }

    public void show(View view) {
        sharedPreferences = getSharedPreferences("my", Context.MODE_PRIVATE);
        Toast.makeText(this, sharedPreferences.getString("what", null), Toast.LENGTH_LONG).show();
    }

猜你喜欢

转载自blog.csdn.net/u014314578/article/details/45365571