I would like to create one class which holds some key values of the app so I can share and access them in all activities. This is how I have done it so far:
I define a class like this:
public class GlobalVars {
public static String str1;
public static String str2;
public static Integer int1;
public static Integer int2;
public static MyDBAdapter myDBAdapter;
public static Boolean isOK1() {
return str1.length() > 3;
}
}
This is how I fill them at the start of the app:
private void getAllInfo() {
// first get the info
Cursor appCursor = cursor;
GlobalVars.str1 = appCursor.getString(appCursor
.getColumnIndexOrThrow(MyDBAdapter.KEY1));
if (GlobalVars.str1 != null) {
} else {
GlobalVars.str1 = "";
}
GlobalVars.int1 = appCursor.getInt(appCursor
.getColumnIndexOrThrow(MyDBAdapter.KEY_NUMBER1));
if (GlobalVars.int1 != null) {
} else {
GlobalVars.int1 = 1;
}
and I access those values normally just by writing
GlobalVars.int1 = ...
or
i = GlobalVars.int1;
wherever I need to
At the very end when the app finishes I put all the values back in the DB.
Is this the best way to handle global variables in this way?
I get really strange NullPointerException Errors when accessing the GlobalVars.int1 variable with users who got the app – while I am 100% the value is always correctly assigned and never with a null.
Do I have to allocate the GlobalVars object before using it?
Is there any possible explanation how those values can become null without me assigning null anywhere?
Thanks
I would recommend to use shared preferences for configuration / shared data storage ( as long as you have reasonable amount of them – database is for potentially unlimited amount )
I work on dependency injector for preferences ( setting values from preferences works already ):
https://github.com/ko5tik/andject
As for your question about null value – if you not assign it, it is null