I've been programming Java for the last two months but I'm experienced programmer in python and C. I know I make errors because of this.
I arrive to this question cleaning of warnings my project in Android studio.
I use a Singleton class with inner classes to keep all my configuration parameters in one place and let all other classes access to it with out the need of passing the configuration.
Here is the basic code of my Singleton
public class syscfg {
public List<CommData> Commlist;
public static CommConfigIP4 MyCommConfig;// = new CommConfig();
private static syscfg instance = null;
private static boolean ConfigStat = false;
/** JAVA singleton control methods**/
protected syscfg(){
// pues eso
if(ConfigStat == false){
Log.i("SD_app_log", "SYSCFG: Module Initialization");
ConfigStat = true;
MyCommConfig = new CommConfigIP4();
init_config();
}else{
Log.i("SD_app_log", "SYSCFG: Module Loaded");
}
}
public static syscfg getInstance(){
if(instance == null){
instance = new syscfg();
}
return instance;
}
public class CommConfigIP4{
public int discoveryPort = 30303;
public byte[] MyMAC;
public String MyType = "";
public String MyIP;
public byte[] getIPbytearray(){
// byte[] IPout= new byte[4];
try{
byte[] IPout = (InetAddress.getByName(MyIP)).getAddress();
return IPout;
}catch (Exception e){
return null;
}
}
In my communications java file/class I have:
public class Communications {
private syscfg CFid ;
...
public Communications(Context ctx){
...
CFid = syscfg.getInstance();
init_comms(); //init_comms calls whoami
}
private void whoami (){
...
CFid.MyCommConfig.MyType = netint.getName();
...
}
}
So, when I first had all elements(variables, classes and methods) in syscfg as static android studio showed a warning saying Static member accessed via instance reference. After some research and documentation I found a recommendation not to use static variables and methods and I tried to eliminate them all. But then I get a nullpointexception error in
CFid.MyCommConfig.MyType = netint.getName();
With the debugger I found that CFid.MyCommConfig = null
I use singleton to avoid using static on syscfg class and access via instantiation and not using the class name.
Now my singleton code is like the one posted here with CommConfigIP4 static and I have the warnings again that recommend me using:
syscfg.MyCommConfig.MyType = netint.getName();
instead of using the instance to acces de configuration.
What is happening here? What I'm missing?
Thanks, Guillermo