【问题标题】:Generate random int and save it to SharedPreferences生成随机整数并将其保存到 SharedPreferences
【发布时间】:2017-07-14 10:00:20
【问题描述】:

当我的应用程序第一次运行时,我需要生成随机 int 以提供设备 ID,然后将其保存到 SharedPrefs,在 TextView 上显示 id,当再次打开时,在 TextView 上显示来自 SharedPeffs 的保存的 ID。

public class MainActivity extends AppCompatActivity {

    public static final String MyPREFERENCES = "MyPrefs";
    public static final String KEY_DEVICE = "id";
    SharedPreferences sharedpreferences;
    String id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        deviceid = (TextView) findViewById(R.id.deviceid);
        sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

        if (!sharedpreferences.contains(id)) {
            SharedPreferences.Editor editor = sharedpreferences.edit();
            id = String.valueOf(new Random().nextInt(900000) + 100000);
            editor.putString(KEY_DEVICE, id);
            editor.commit();
            deviceid.setText(id);
        }

        deviceid.setText(id);
    }
}

以上代码生成随机int并显示在TexView上,但每次我隐藏或关闭应用程序时,设备id都会改变 你能解释一下我必须做些什么来实现我的目标。

【问题讨论】:

  • contains 第一个参数是键,而不是值。你的密钥是KEY_DEVICE,你为什么要检查id
  • stackoverflow.com/questions/7496840/… 请转到链接并了解如何获取 sharedpreferences 值..

标签: java android sharedpreferences


【解决方案1】:

应该有"id"KEY_DEVICE

替换

!sharedpreferences.contains(id)

!sharedpreferences.contains(KEY_DEVICE)

还有

deviceid.setText(id);

在这种情况下将显示null

所以你必须在setText之前添加

id = sharedpreferences.getString(KEY_DEVICE,"0");

【讨论】:

    【解决方案2】:

    试试这个

    String MyPREFERENCES = "MyPrefs";
            String KEY_DEVICE = "device_id";
            SharedPreferences sharedpreferences;
            SharedPreferences.Editor editor;
    
            sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
            if (sharedpreferences.contains(KEY_DEVICE)) {
                id = sharedpreferences.getString(KEY_DEVICE, "0");
                deviceid.setText(id);
            } else {
                id = String.valueOf(new Random().nextInt(900000) + 100000);
                editor = sharedpreferences.edit();
                editor.putString(KEY_DEVICE, id);
                editor.apply();
                deviceid.setText(id);
            }
    

    【讨论】:

      【解决方案3】:

      这是因为您只是检查是否没有共享偏好值,然后选择一个随机数并将其添加到设备中,但您在 on create 方法中没有获得任何值,即您没有获得任何共享偏好值之前存储的。只需获取您存储的值,然后检查该值是否存在,如果存在则在 textview 中设置,否则调用条件检查。希望对你有帮助

      【讨论】:

        【解决方案4】:

        在从 sharedPreferences 获取值之前检查 null。 如果为 null :则保存 id
        else : 只获取旧的。

        如果需要此检查:if(!sharedpreferences.contains(id)),则将其嵌套在 null 检查下。

        【讨论】:

          猜你喜欢
          • 2011-05-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-10-09
          • 2014-08-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多