【问题标题】:Making a variable value constant in android studio在android studio中制作变量值常量
【发布时间】:2017-10-11 06:41:51
【问题描述】:
我对 android 编码非常陌生,所以我几乎不知道任何语法。我在 MainActivity.java 中定义一个变量并为其分配一个随机的 4 位值。我只想在安装/更新应用程序时分配此值一次,而不是每次用户打开应用程序时。如果你们中的任何人知道解决此问题的方法,请帮助我。以下是我目前的代码
Random r = new Random();
int i1 = r.nextInt(9999 - 1) + 1;
【问题讨论】:
标签:
android
android-studio
constants
【解决方案1】:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString("key for value", somrRandonNumber);
editor.putBoolean("is first lunch", false);
editor.commit();
然后用
检索它
int number = sharedPref.getInt("key for value";
有时您需要指定一个默认值,例如:
SharedPref.getBoolean("is first lunch",true);
祝你好运
【解决方案2】:
使用 SharedPreference 来保存价值使用此代码
int i1=0;
if (getIntValue() == 0) {
Random r = new Random();
i1 = r.nextInt(9999 - 1) + 1;
saveIntValue(i1);
} else {
i1 = getIntValue();
}
这里有两种方法
public void saveIntValue(int myIntValue) {
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("your_int_key", myIntValue);
editor.commit();
}
public int getIntValue() {
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
int myIntValue = sp.getInt("your_int_key", 0);
if (myIntValue == 0) {
return 0;
} else {
return myIntValue;
}
}
【解决方案3】:
如果值为 0,则存储在 Preference 中,否则获取存储的值
Random r = new Random();
int value= r.nextInt(9999 - 1) + 1;
if(getValue()==0)
PreferenceManager.getDefaultSharedPreferences(context).edit()
.putInt("uniqueInt", value).apply();
else {
int uniqueIntFromPref = getValue();
}
从首选项中检索
private int getValue() {
return PreferenceManager
.getDefaultSharedPreferences(context)
.getString("uniqueInt", 0);
}
只需复制并粘贴上面的代码