为共享preferences Android的默认值 [英] android default values for shared preferences

查看:119
本文介绍了为共享preferences Android的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想明白了Android的共享preferences。我是一个初学者
不知道了很多关于它。

I am trying to understand the SharedPreferences of Android. I am a beginner and don't know a lot about it.

我有这个类我为我的应用程序preferences实施

I have this class I implemented for my app Preferences

public class Preferences {
    public static final String MY_PREF = "MyPreferences";

    private SharedPreferences sharedPreferences;
    private Editor editor;

    public Preferences(Context context) {
        this.sharedPreferences = context.getSharedPreferences(MY_PREF, 0);
        this.editor = this.sharedPreferences.edit();
    }

    public void set(String key, String value) {
        this.editor.putString(key, value);
        this.editor.commit();
    }

    public String get(String key) {
        return this.sharedPreferences.getString(key, null);
    }

    public void clear(String key) {
        this.editor.remove(key);
        this.editor.commit();
    }

    public void clear() {
        this.editor.clear();
        this.editor.commit();
    }
}

的事情是,我想设置默认preferences。当安装应用程序,并且可以由应用程序后修改,并坚持不懈,他们将被设置。
我听到了preferences.xml,但我不明白的过程。

The thing is that I would like to set default preferences. They would be set when the app is installed and could be modified after by the application and stay persistent. I heard about a preferences.xml but I don't understand the process.

有人能帮助我吗?

感谢您的时间

推荐答案

简单,如果你想为每个变量单独的默认值,你需要做的是为每一个,但你的方法:

Simple, if you want a separate default value for each variable, you need to do it for each one, but on your method:

 public String get(String key) {
    return this.sharedPreferences.getString(key,"this is your default value");
}

如果变量从未被用户accesed或者从未被创建,系统将设置为值默认值,如果您或用户改变了这个值,默认值被忽略。看看这个: http://developer.android.com /guide/topics/data/data-storage.html#$p$pf

if the variable was never accesed by the user or was never created, the system will set as value the default value and if you or the user changed this value, the default value is ignored. Look this: http://developer.android.com/guide/topics/data/data-storage.html#pref

从Android电子文档的直接:共享preferences类提供了一个总体框架,使您可以保存和检索的原始数据类型的持久键 - 值对。您可以使用共享preferences保存任何基本数据:布尔型,浮点数,整型,长整型和字符串。该数据将在用户会话持久(即使你的应用程序被杀害)。

Direct from Android Documentation: The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).

这篇关于为共享preferences Android的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆