保存并读取int-android

保存并读取int-android,android,save,int,Android,Save,Int,我正在制作一个设置屏幕,使用int设置我的应用程序的背景。它工作得很好。。。在当前活动的内部。但一旦我离开活动,int值就会丢失,背景也不会改变 我想做什么:我想保存设置活动中的int,然后将其导入其他活动,并检查int“bak”是否等于null、“bg”、“bg1”或“bg2” 我听说过SharedReferences,但从未让它发挥作用。这就是我打开一个新线程的原因 好的,添加这些全局变量 SharedPreferences data; public static String filena

我正在制作一个设置屏幕,使用int设置我的应用程序的背景。它工作得很好。。。在当前活动的内部。但一旦我离开活动,int值就会丢失,背景也不会改变

我想做什么:我想保存设置活动中的int,然后将其导入其他活动,并检查int“bak”是否等于null、“bg”、“bg1”或“bg2”


我听说过SharedReferences,但从未让它发挥作用。这就是我打开一个新线程的原因

好的,添加这些全局变量

SharedPreferences data;
public static String filename = "whateveryou want";
在onCreate中初始化它

data = getSharedPreferences(filename, 0);
然后,要添加一些内容,请使用它,其中
“key”
是唯一的描述符,
name
是要存储的变量名

        SharedPreferences.Editor editor = data.edit();
        editor.putInt("key", name);
        editor.commit();
通过此访问它,其中
默认值
是您希望在不存在首选项的情况下分配变量的值

intVariable = data.getInt("key", default);
编辑:

我注意到您需要使用字母,例如bg1等。要做到这一点,您需要使用字符串,或者使用带开关大小写的int或多个if语句。下面是一个可以修改的开关案例示例。只需确保将switch case语句放在访问上一个代码块中的SharedReference之后

switch (integerVariable){
    case 1: // if the intagerVariable = 1, notice the : not a ;
        // set background to BG1
    break;
    case 2: // if the intagerVariable = 2, notice the : not a ;
        // set background to BG2
    break;
}

只要根据需要添加尽可能多的case语句。

好的,添加这些全局变量

SharedPreferences data;
public static String filename = "whateveryou want";
在onCreate中初始化它

data = getSharedPreferences(filename, 0);
然后,要添加一些内容,请使用它,其中
“key”
是唯一的描述符,
name
是要存储的变量名

        SharedPreferences.Editor editor = data.edit();
        editor.putInt("key", name);
        editor.commit();
通过此访问它,其中
默认值
是您希望在不存在首选项的情况下分配变量的值

intVariable = data.getInt("key", default);
编辑:

我注意到您需要使用字母,例如bg1等。要做到这一点,您需要使用字符串,或者使用带开关大小写的int或多个if语句。下面是一个可以修改的开关案例示例。只需确保将switch case语句放在访问上一个代码块中的SharedReference之后

switch (integerVariable){
    case 1: // if the intagerVariable = 1, notice the : not a ;
        // set background to BG1
    break;
    case 2: // if the intagerVariable = 2, notice the : not a ;
        // set background to BG2
    break;
}

只需根据需要添加尽可能多的case语句。

int在导入时将命名为“key”,还是保留以前的名称?(Bak)您可以用您命名的任何名称导入它,并且它将被命名为您用于
name=getString(key,default)
THX的任何变量!它在我的代码中起作用。不过,对打算使用此代码的任何人的建议是记住pass.edit();应替换为(在本例中)data.edit();或者你只是想知道“pass”有什么问题。int在导入时会被命名为“key”还是保留了它以前的名称?(Bak)您可以用您命名的任何名称导入它,并且它将被命名为您用于
name=getString(key,default)
THX的任何变量!它在我的代码中起作用。不过,对打算使用此代码的任何人的建议是记住pass.edit();应替换为(在本例中)data.edit();或者你会想“通行证”有什么问题。