如何保存接口数据



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

Thanks for the help

如果你想保存原始数据类型(字符串,int,布尔值等)使用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", "");

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检索或存储该数据。

最新更新