【问题标题】:activity onPause how to save the interface dataactivity onPause如何保存界面数据
【发布时间】:2013-03-28 13:56:24
【问题描述】:

您好,我的应用中有 2 个活动,我希望当我在它们之间切换时,用户界面和变量不会改变,有什么办法可以做到这一点。

感谢您的帮助

【问题讨论】:

标签: android android-activity onresume onpause


【解决方案1】:

如果您想保存原始数据类型(字符串、整数、布尔值等),请使用 SharedPreferences,这将永久保存您的值,直到用户重新安装(清除数据)应用程序。共享首选项的工作原理是这样的

// save string in sharedPreferences
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putString("some_key", string); // here string is the value you want to save
                    editor.commit(); 

// 恢复sharedPreferences中的字符串

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
string = settings.getString("some_key", "");

【讨论】:

    【解决方案2】:

    SharedPreferences 似乎是您实现它的最简单方法,因为您可以使用 SharedPreferences 方法永久保存任何内容(嗯,任何基本数据类型)。

    /**
     * Retrieves data from sharedpreferences
     * @param c the application context
     * @param pref the preference to be retrieved
     * @return the stored JSON-formatted String containing the data 
     */
    public static String getStoredJSONData(Context c, String pref) {
        if (c != null) {
            SharedPreferences sPrefs = c.getSharedPreferences("AppPreferences", Context.MODE_PRIVATE);
            return sPrefs.getString(pref, null);
        }
        return null;
    }
    
    /**
    * Stores the most recent data into sharedpreferences
    * @param c the application context
    * @param pref the preference to be stored
    * @param policyData the data to be stored
    */
    public static void setStoredJSONData(Context c, String pref, String policyData) {
        if (c != null) {
            SharedPreferences sPrefs = c.getSharedPreferences("AppPreferences", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sPrefs.edit();
            editor.putString(pref, policyData);
            editor.commit();
        }
    }
    

    字符串 'pref' 是一个标签,用于引用该特定数据,例如:“taylor.matt.data1”将引用一个数据,可用于从中检索或存储它共享首选项。

    【讨论】:

    • 有更好的方法来处理大量数据,因为我有 30 个 int、10 个 double 和 10 个微调器位置。
    • 您可以将所有这些数据存储在单个 JSON 对象中,然后存储和检索它,但无论是作为共享首选项还是作为变量,它都会占用内存
    • 怎么加双倍值
    • SharedPreferences.Editor 有一个.putFloat() 方法。根据您的可变精度,您可以使用它,也可以将其存储为字符串,然后在检索时解析它
    猜你喜欢
    • 2012-01-14
    • 2015-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多