【问题标题】:SharedPreferences for storing an int用于存储 int 的 SharedPreferences
【发布时间】:2014-12-09 00:07:11
【问题描述】:

只是一个简单的问题。我需要在我的应用程序中存储一个 int,而 SharedPreferences 将是一种简洁而简单的方法。对使用它有任何异议吗?这是我的代码:

private SharedPreferences pref;
private Editor editor;
//-------------------------------
//get the best
pref = PreferenceManager.getDefaultSharedPreferences(this);
editor = pref.edit();
best = pref.getInt("value", 0);
//-------------------------------
//save the best
best = pref.getInt("value", best);
if(best < now){
    editor.putInt("value", now);
    editor.commit();

【问题讨论】:

    标签: android sharedpreferences


    【解决方案1】:

    这样存储:

    SharedPreferences pref = getSharedPreferences("prefs", Activity.MODE_PRIVATE);
    SharedPreferences.Editor edt = pref.edit();
    edt.putInt("key", i); // i is integer
    edt.commit();
    

    要使用它:

    SharedPreferences pref = getSharedPreferences("prefs", Activity.MODE_PRIVATE);
    int i = pref.getInt("key", -1);
    

    【讨论】:

    • 谢谢 :) 我真的不知道内存是如何与 SharedPreferences 一起使用的。即使卸载应用程序后,该值是否仍保留在内存中?一个 int 并不多,但仍然。
    • 卸载应用时删除。但是有一些方法可以存储SharedPreferences。您可以备份到云端查看stackoverflow.com/q/9815363/3879470 : You should add a BackupAgentHelper to your app. Together with the SharedPreferenceBackupHelper, it backups the SharedPreferences to the cloud (if the device supports it). When the app is reinstalled the data is restored.
    • 另见:stackoverflow.com/q/15873066/3879470When you uninstall any application all the changes the application have made in your internal memory are revoked, that means your SharedPreference files, Other data files, Database file, Application gets removed automatically by the Android OS.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2017-03-19
    • 1970-01-01
    • 2017-10-06
    相关资源
    最近更新 更多