In my android app there are certain common tasks for example fetching the IP of server to make API calls - For this I have created a singleton class
public class MiscFunctions extends Activity {
private static MiscFunctions ourInstance = new MiscFunctions();
public static MiscFunctions getInstance() {
return ourInstance;
}
private MiscFunctions() {
}
/*
method to return the ip of main server.
The ip is written in plain text in file server_url.txt in assets folder
*/
public String getServerIP(Context c) {
try {
AssetManager am = c.getAssets();
InputStream is = am.open("server_url.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
return new String(buffer);
}
catch (IOException e) {
System.out.println("IO Error while accesssing server_url.txt");
e.printStackTrace();
return "Failed to open server_url.txt";
}
catch (NullPointerException e) {
System.out.println("NullPointer exception error while accessrng server_url.txt");
e.printStackTrace();
return "Failed to open server_url.txt";
}
catch (Exception e) {
System.out.println("Unknown exception error while accessrng server_url.txt");
e.printStackTrace();
return "Failed to open server_url.txt";
}
}
}
Then I will be using this class in various activities like this:
Context c = this.getApplicationContext();
server_ip = MiscFunctions.getInstance().getServerIP(c);
I am just wondering whether this is the correct approach? Or I should be using a regular java class and instantiate that class to call methods in activities.
Which approach would be more efficient and robust?
Any expert comments would be highly appreciated. Thanks in advance