activity onPause如何保存接口数据

时间:2013-03-28 13:56:25

标签: android android-activity onresume onpause

您好我的应用程序有2个活动,我希望当我在它们之间切换时,用户界面和变量不会改变是否有任何方法可以做到。

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

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”将引用一段数据,可用于检索或存储它SharedPreferences。

答案 1 :(得分:1)

如果要保存原始数据类型(string,int,boolean等..),请使用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", "");
相关问题