简体   繁体   中英

Android preferences not working

I'm new to the amazing world of java, but my Obj-C experince tells me that this code:

Preferences prefs = Preferences.userRoot();
String tickets = prefs.get("tickets", "???");
Log.d("Prefs", tickets);
prefs.put("tickets", "!!!");

should produce ??? on the first run, and !!! on the second run. But it does not. I see ??? all the time.

What am I missing? Maybe some permissions? Maybe calling some save() method on prefs object?

I've also tried:

Preferences prefs = Preferences.userRoot().node(this.getClass().getName());

No luck either.

I think you're probably looking for SharedPreferences ... " context " is your Activity or Application

try:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String tickets = prefs.getString("tickets", "???");
Log.d("Prefs", tickets);
prefs.edit().putString("tickets", "!!!").commit();

Seems like you want to use SharedPreferences to store some data. In order to write to preferences try this function:

public void putPref(Context context, String key, String value){
    SharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = SharedPrefs.edit();
    editor.putString(key, value);
    editor.commit();
}

If you want to put the value "???" using key "tickets" use:

putPref(context, "tickets", "???");

You can retrieve that value by using:

SharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);

If you want to get value for the key "ticket" use:

SharedPrefs.getString("tickets", "default");

where "default" is the default value if the preference isn't found. Hope this helps.

You can save the values to preference using the below function

public static void saveTickets(String customerId,Context context) 
        {
            SharedPreferences preferences;
            preferences = context.getSharedPreferences("sample",Context.MODE_PRIVATE);
            preferences.edit().putString("tickets", customerId).commit();
        }

Get the values from preference using the below function. The parameter you need to pass is just context

public static String getTickets(Context context) 
    {
        SharedPreferences preferences;
        preferences = context.getSharedPreferences("sample",Context.MODE_PRIVATE);
        String  customerId = preferences.getString("tickets", "");
        return customerId;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM