Store data to shared preferences

private static final String MY_PREFS = "mypreferences"; private static final String USERNAME = "username"; private static String mUsername = null; public static String getUsername() { if (mUsername == null) { SharedPreferences sp = Utils.getContext().getSharedPreferences(MY_PREFS, Context.MODE_PRIVATE); mUsername = sp.getString(USERNAME, null); } return mUsername; } public static void setUsername(String username) { SharedPreferences sp = Utils.getContext().getSharedPreferences(MY_PREFS, Context.MODE_PRIVATE); Editor editor = sp.edit(); if (username != null && !"".equals(username)) { mUsername = username; editor.putString(USERNAME, username).apply(); } else { mUsername = null; } }
Store data using Android’s SharedPreferences and retrieve the data using static variables.

#android #sharedPreferences #java #data

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.