Hello I have in my app 2 activities and I want that when I switch between them the user interface and the Variables wont change is there any way to do it.

Thanks for the help

有帮助吗?

解决方案

If you want to save primitive data type (string,int,boolean etc.. ) use SharedPreferences, that will save your values permanently, untill user reinstall (clear data) application. Shared Preferences works like this

// 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(); 

// restore string in sharedPreferences

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

其他提示

SharedPreferences seem like the simplest way for you to achieve it, as you can use the SharedPreferences methods to save anything (well, any basic datatype) persistently.

/**
 * 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();
    }
}

Where the string 'pref' is a tag used to refer to that specific piece of data, so for example: "taylor.matt.data1" would refer to a piece of data and could be used to retrieve or store it from SharedPreferences.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top