I'm new to Programming and Java and building a small Application in JAVA with SQL and UI(Jframes)
In the log-in frame after the user enters his user name and password I do a SQL select query to search USER table for this user. If the query returns 1 single row, the login button event handler triggers and the object of the next frame is created.
few frames later I have an SQL insert activity where I also have to insert the USER_ID of the person initiating the insert(the current logged in user).
What is the best practice to pass this information across a series of frame classes?
My initial idea is to pass the user_id as a parameter in the object so it gets set in the constructor of each frame class. but the problem is not all my frames really need this data. Only the final frame involved with the insertion needs the user ID. but in-order to get to that frame I have to pass through all other frames.
This doesn't seem like a good practice.
First Approach
The first possibility I thought of was to use java.util.Properties to store the application state inside of a properties file. The approach would be to use a singleton wrapper, let's say ApplicationState for reading/writing to properties file. This singleton class would be reachable from all frames, alternatively an instance of this class could be passed inside of constructor.
public class ApplicationState {
private static ApplicationState instance = new ApplicationState();
private ApplicationState() { }
public static ApplicationState getInstance( ) { return instance; }
public String read(String key) throws IOException {
try (InputStream input = new FileInputStream("path/to/config.properties")) {
Properties prop = new Properties();
prop.load(input);
return prop.getProperty(key);
}
}
...
}
Second Approach
Then I realized that a much cleaner solution would be to use the java.util.prefs.Preferences API. See Preferences API for details.
class A {
public void login() {
Preferences prefs = Preferences.userNodeForPackage(com.mycompany.MyClass.class);
prefs.putInt("userId", 11);
...
}
}
class B {
public void insert() {
Preferences prefs = Preferences.userNodeForPackage(com.mycompany.MyClass.class);
int userId = prefs.getInt("userId", 0); // 0 is default identifier
...
}
}
In addition because you want to store sensitive information, encrypted storage would be useful. For using encrypted preferences see this article.
hi guys im writing a method that contains a string name from other classes..
i use the String apkName and mcurrentPhotoPath in alot of activites but need to pass the value of them string into my download method.
ive tried this
public static class Stringz{
public String APK() {
return apkNames;
}
public String FILEPATH() {
return mCurrentPhotoPath;
}
}
then in my download method i use
Stringz st = new Stringz();
String apkNames = st.APK();
String mCurrentPhotoPath = st.FILEPATH();
which works fine for a single activity. but because i have multiple activites using the same string names how can i write it so my method know which string to look for in every activity
thanks guys
You need one of these two:
1) An instance of Stringz
2) A static reference to the Strings you want to access
A static reference you define as:
public static String yourString = "Some string";
And instance:
public Stringz reference = new Stringz();
//and access like:
reference.yourString;
I have two classes, one loggedIn, and a User class. In the loggedIn class I want to show the shared preferences that I made when the user logs in.
loginPrefs = getSharedPreferences("loginpreferences",Context.MODE_PRIVATE);
SharedPreferences.Editor loginEditor = loginPrefs.edit();
loginEditor.putString("userID", userIDCrypt);
loginEditor.commit();
Now i want to make in the user class a getID() method, that I can call the method from every class with User.getID();. How can I do this?
I need the userID in multiple classes, so I want one activity (called getID e.g.) that gives me the user ID.
try this in one Activity :
SharedPreferences sp;
SharedPreferences.Editor edit;
sp = getSharedPreferences("enter", MODE_PRIVATE);
edit = sp.edit();
edit.putString("name", username);
edit.putString("pwd", password);
edit.commit();
in next activity :
SharedPreferences sp = getSharedPreferences("enter", MODE_PRIVATE);
sp.getString("name", "default value"));
sp.getString("pwd", "default value"));
do like this make one class for your sharedpreference
public class Session {
private SharedPreferences prefs;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
}
public void setusename(String usename) {
prefs.edit().putString("usename", usename).commit();
prefsCommit();
}
public String getusename() {
String usename = prefs.getString("usename","");
return usename;
}
}
now after making this class when u want to use this use like this
make object og this class like
private Session session;//global variable
session = new Session(cntx); //in oncreate
and now we set sharedpreference then use this like
session.setusename("USERNAME");
now when ever u want to get username then same work for session object and call this
session.getusename();
best of luck :) same for password
Sorry if there is any syntax or compilation issues, just typing out of my head, and might make some mistakes. So in essence this is an approach that you can use to expose your prefs from one simple class and access it from any where.
public class MySharedPrefs {
public SharedPreferences sp;
public MySharedPrefs()
{
this.sp = c.getSharedPreferences("prefs", Context.MODE_PRIVATE);
}
public static String getStringFieldValue(Context c, String fieldName)
{
MySharedPrefs p = new MySharedPrefs(c);
return p.sp.getString(fieldName, "default value");
}
public static void setStringValue(Context c, String fieldName, String value)
{
MySharedPrefs p = new MySharedPrefs(c);
SharedPreferences.Editor edit;
edit = p.sp.edit();
edit.putString(fieldName, value);
edit.commit();
}
}
Then use it like this in your activity:
MySharedPrefs.getStringFieldValue(this, "name");
You can the also expand on this class and add additional helper methods such as a getUserName or etc.
UPDATE:
When calling this from another static class, that class needs to have a reference to your applications context, you then need to provide that context to this function instead of using this.
MySharedPrefs.getStringFieldValue(context, "name"); //if your other static class has a property called context that contains your applications context
so I've been working on a project that receives data from server, for example sessionKey. I created getter and setter method like this :
public class sEngine
{
private static String sessionKey;
public static String getSessionKey() {
return sessionKey;
}
public static void setSessionKey(
String sessionKey) {
sEngine.sessionKey = sessionKey;
}
}
Then I have activity A. In this activity A, I insert a value into the setter method.
public class A extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
sEngine.setSessionKey("Hello world")
}
}
I also have activity B. In this activity B, I call the getter method
public class B extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
String sessionKey = sEngine.getSessionKey();
}
}
It occurs to me, that Android sometimes wipes all the data in order to free some memory, for example when I let the program idle for too long, or I used Advanced Task Killer. The problem is if those happen, I will get null in activity B when I call the getter method although I've set the value in activity A. Is there any way for me to maintain the value stored via the setter method (other than using SharedPreference) so the value will still be there although Android wipes the memories/data?
Is there any way for me to maintain the value stored via the setter
method (other than using SharedPreference) so the value will still be
there although Android wipes the memories/data?
Not sure why you wouldn't want to use SharedPreferences, despite it being the perfect candidate in your requirement. When somethings as simple as this can store it:
SharedPreferences sharedPrefs = getApplicationContext().getSharedPreferences(SOME_KEY, Context.MODE_PRIVATE);
Editor editor = sharedPrefs.edit();
editor.putString("session_key", sessionKey );
This will ensure your sessionkey always remains stored for easy retrieval. Unless the user clears your app data that is.
Your only alternatives as opposed to SharedPreferences are saving the sessionkey to a Database which in my opinion, considering the task it will perform, is absolutely unnecessary.
You could also consider writing the sessionkey to a text file and then read it to retrive the data.
Both the alternatives to SharedPreferences are truly unfit for the purpose you need it for. And I would really urge you to re-consider using SharedPreferences .
Try this, Declare you non activity class in A Activity. and then set your session value.
sEngine mengine = new sEngine();
mengine.setSessionKey("Hello world");
And also get session value in B activity.
sEngine mengine = new sEngine();
String str = mengine.getSessionKey();
change
sEngine.sessionKey = sessionKey;
in your code to
this.sessionKey = sessionKey;
or simply
sessionKey = sessionKey;
using sEngine. makes one believe that your class is static.Which it isnt!
or if you want to use this sEngine. everywhere in your code you need to declare this class as static.In that case you just need to make the class declaration to static:
public static class sEngine {
In an application I have been building we rely on SharedPreferences quite a bit, this got me thinking about what is best practice when it comes to accessing SharedPreferences. For instance many people say the appropriate way to access it is via this call:
PreferenceManager.getDefaultSharedPreferences(Context context)
However it seems like this could be dangerous. If you have a large application that is relying on SharedPreferences you could have key duplication, especially in the case of using some third party library that relies on SharedPreferences as well. It seems to me that the better call to use would be:
Context.getSharedPreferences(String name, int mode)
This way if you have a class that heavily relies on SharedPreferences you can create a preference file that is used only by your class. You could use the fully qualified name of the class to ensure that the file will most likely not be duplicated by someone else.
Also based on this SO question: Should accessing SharedPreferences be done off the UI Thread?, it seems that accesses SharedPreferences should be done off the UI thread which makes sense.
Are there any other best practices Android developers should be aware of when using SharedPreferences in their applications?
I've wrote a little article that can also be found here. It describes what SharedPreferences is :
Best Practice: SharedPreferences
Android provides many ways of storing application data. One of those ways leads us to the SharedPreferences object which is used to store private primitive data in key-value pairs.
All logic are based only on three simple classes:
SharedPreferences
SharedPreferences.Editor
SharedPreferences.OnSharedPreferenceChangeListener
SharedPreferences
SharedPreferences is main of them. It's responsible for getting (parsing) stored data, provides interface for getting Editor object and interfaces for adding and removing OnSharedPreferenceChangeListener
To create SharedPreferences you will need Context object (can be an application Context)
getSharedPreferences method parses Preference file and creates Map object for it
You can create it in few modes provided by Context. You should always use MODE_PRIVATE, as all the other modes are deprecated since API level 17.
// parse Preference file
SharedPreferences preferences = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
// get values from Map
preferences.getBoolean("key", defaultValue)
preferences.get..("key", defaultValue)
// you can get all Map but be careful you must not modify the collection returned by this
// method, or alter any of its contents.
Map<String, ?> all = preferences.getAll();
// get Editor object
SharedPreferences.Editor editor = preferences.edit();
//add on Change Listener
preferences.registerOnSharedPreferenceChangeListener(mListener);
//remove on Change Listener
preferences.unregisterOnSharedPreferenceChangeListener(mListener);
// listener example
SharedPreferences.OnSharedPreferenceChangeListener mOnSharedPreferenceChangeListener
= new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
}
};
Editor
SharedPreferences.Editor is an Interface used for modifying values in a SharedPreferences object. All changes you make in an editor are batched, and not copied back to the original SharedPreferences until you call commit() or apply()
Use simple interface to put values in Editor
Save values synchronous with commit() or asynchronous with apply which is faster. In fact of using different threads using commit() is safer. Thats why I prefer to use commit().
Remove single value with remove() or clear all values with clear()
// get Editor object
SharedPreferences.Editor editor = preferences.edit();
// put values in editor
editor.putBoolean("key", value);
editor.put..("key", value);
// remove single value by key
editor.remove("key");
// remove all values
editor.clear();
// commit your putted values to the SharedPreferences object synchronously
// returns true if success
boolean result = editor.commit();
// do the same as commit() but asynchronously (faster but not safely)
// returns nothing
editor.apply();
Performance & Tips
SharedPreferences is a Singleton object so you can easily get as many references as you want, it opens file only when you call getSharedPreferences first time, or create only one reference for it.
// There are 1000 String values in preferences
SharedPreferences first = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
// call time = 4 milliseconds
SharedPreferences second = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
// call time = 0 milliseconds
SharedPreferences third = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
// call time = 0 milliseconds
As SharedPreferences is a Singleton object you can change any of It's instances and not be scared that their data will be different
first.edit().putInt("key",15).commit();
int firstValue = first.getInt("key",0)); // firstValue is 15
int secondValue = second.getInt("key",0)); // secondValue is also 15
Remember the larger the Preference object is the longer get, commit, apply, remove and clear operations will be. So it's highly recommended to separate your data in different small objects.
Your Preferences will not be removed after Application update. So there are cases when you need to create some migration scheme. For example you have Application that parse local JSON in start of application, to do this only after first start you decided to save boolean flag wasLocalDataLoaded. After some time you updated that JSON and released new application version. Users will update their applications but they will not load new JSON because they already done it in first application version.
public class MigrationManager {
private final static String KEY_PREFERENCES_VERSION = "key_preferences_version";
private final static int PREFERENCES_VERSION = 2;
public static void migrate(Context context) {
SharedPreferences preferences = context.getSharedPreferences("pref", Context.MODE_PRIVATE);
checkPreferences(preferences);
}
private static void checkPreferences(SharedPreferences thePreferences) {
final double oldVersion = thePreferences.getInt(KEY_PREFERENCES_VERSION, 1);
if (oldVersion < PREFERENCES_VERSION) {
final SharedPreferences.Editor edit = thePreferences.edit();
edit.clear();
edit.putInt(KEY_PREFERENCES_VERSION, currentVersion);
edit.commit();
}
}
}
SharedPreferences are stored in an xml file in the app data folder
// yours preferences
/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PREFS_NAME.xml
// default preferences
/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PACKAGE_NAME_preferences.xml
Android guide.
Sample Code
public class PreferencesManager {
private static final String PREF_NAME = "com.example.app.PREF_NAME";
private static final String KEY_VALUE = "com.example.app.KEY_VALUE";
private static PreferencesManager sInstance;
private final SharedPreferences mPref;
private PreferencesManager(Context context) {
mPref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
}
public static synchronized void initializeInstance(Context context) {
if (sInstance == null) {
sInstance = new PreferencesManager(context);
}
}
public static synchronized PreferencesManager getInstance() {
if (sInstance == null) {
throw new IllegalStateException(PreferencesManager.class.getSimpleName() +
" is not initialized, call initializeInstance(..) method first.");
}
return sInstance;
}
public void setValue(long value) {
mPref.edit()
.putLong(KEY_VALUE, value)
.commit();
}
public long getValue() {
return mPref.getLong(KEY_VALUE, 0);
}
public void remove(String key) {
mPref.edit()
.remove(key)
.commit();
}
public boolean clear() {
return mPref.edit()
.clear()
.commit();
}
}
If you have a large application that is relying on SharedPreferences you could have key duplication, especially in the case of using some third party library that relies on SharedPreferences as well.
Libraries should not use that particular SharedPreferences. The default SharedPreferences should only be used by the application.
This way if you have a class that heavily relies on SharedPreferences you can create a preference file that is used only by your class.
You are certainly welcome to do this. I wouldn't, at the application level, as the primary reason for SharedPreferences is to have them be shared among the components in the application. A development team should have no problem managing this namespace, just as they should have no problem managing names of classes, packages, resources, or other project-level stuff. Moreover, the default SharedPreferences are what your PreferenceActivity will use.
However, going back to your libraries point, reusable libraries should use a separate SharedPreferences for their library only. I would not base it on a class name, because then you are one refactoring away from breaking your app. Instead, pick a name that is unique (e.g., based on the library name, such as "com.commonsware.cwac.wakeful.WakefulIntentService") but stable.
it seems that accesses SharedPreferences should be done off the UI thread which makes sense.
Ideally, yes. I recently released a SharedPreferencesLoader that helps with this.
Are there any other best practices Android developers should be aware of when using SharedPreferences in their applications?
Don't over-rely upon them. They are stored in XML files and are not transactional. A database should be your primary data store, particularly for data you really don't want to lose.
In kotlin, use of SharedPreferences can be simplified in the following way.
class Prefs(context: Context) {
companion object {
private const val PREFS_FILENAME = "app_prefs"
private const val KEY_MY_STRING = "my_string"
private const val KEY_MY_BOOLEAN = "my_boolean"
private const val KEY_MY_ARRAY = "string_array"
}
private val sharedPrefs: SharedPreferences =
context.getSharedPreferences(PREFS_FILENAME, Context.MODE_PRIVATE)
var myString: String
get() = sharedPrefs.getString(KEY_MY_STRING, "") ?: ""
set(value) = sharedPrefs.edit { putString(KEY_MY_STRING, value) }
var myBoolean: Boolean
get() = sharedPrefs.getBoolean(KEY_MY_BOOLEAN, false)
set(value) = sharedPrefs.edit { putBoolean(KEY_MY_BOOLEAN, value) }
var myStringArray: Array<String>
get() = sharedPrefs.getStringSet(KEY_MY_ARRAY, emptySet())?.toTypedArray()
?: emptyArray()
set(value) = sharedPrefs.edit { putStringSet(KEY_MY_ARRAY, value.toSet()) }
Here, sharedPrefs.edit{...} is provided by the android core ktx library and should be implemented by adding dependency implementation "androidx.core:core-ktx:1.0.2" in appliation level build.gradle.
You can get the instance of SharedPreferences by using code:
val prefs = Prefs(context)
Furthermore, you can create the Singleton object of Prefs and use from anywhere within the app.
val prefs: Prefs by lazy {
Prefs(App.instance)
}
where, App extends Application and should be included in AndroidManifest.xml
App.kt
class App:Application() {
companion object {
lateinit var instance: App
}
override fun onCreate() {
super.onCreate()
instance = this
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest .....
<application
android:name=".App"
....
Example Usage:
// get stored value
val myString = prefs.myString
// store value
prefs.myString = "My String Value"
// get stored array
val myStringArray = prefs.myStringArray
// store array
prefs.myStringArray = arrayOf("String 1","String 2","String 3")
This is my way
for write
SharedPreferences settings = context.getSharedPreferences("prefs", 0);
SharedPreferences.Editor editore = settings.edit();
editore.putString("key", "some value");
editore.apply();
to read
SharedPreferences settings = getSharedPreferences("prefs", 0);
Strings value = settings.getString("key", "");
Let's assume in a project, with multiple developers working on it, they are defining SharedPreference within an Activity like this:
SharedPreferences sharedPref = context.getSharedPreferences("prefName", 0);
At one point or another two developers can define the SharedPreference with the same name or insert equivalent Key - Value pairs, which will lead to problems in using the keys.
The solution relies on two options, whether to use;
SharedPreferences Singleton that uses String keys.
SharedPreferences Singleton that uses Enum keys.
Personally and According to this Sharepreference Documentation, I prefer to use Enum keys as it enforces stricter control when there are multiple programmers working on a project. A programmer has no choice but to declare a new key in the appropriate enum class and so all the keys are in the same place.
And to avoid boilerplate code writing create the SharedPreference singleton.
This SharedPreferences singleton Class help to centralize and simplify reading and writing of SharedPreferences in your Android app.
The source code for the two provided solutions can be found in GitHub