I'm a little bit new to Android. If I have a Singleton below does the init function automatically get called when the singleton is first initialsed?
public class Singleton {
private static Singleton INSTANCE = null;
private Singleton() {};
public static Singleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
return(INSTANCE);
}
void init() {
Log.d(TAG, "is this firing");
}
}
I'm referencing the Singleton the first time in the MainActivity but I can't see the output "is this firing" in the LogCat:
public class MainActivity extends Activity {
Singleton model;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
model = Singleton.getInstance();
}
}
I've used swift/ios a bit and in an ios app when I call Singleton.sharedInstance for the first time init() runs and things get initialized. I can't recall what happens in Java.
class Singleton {
private struct Static {
static var instance: Singleton?
}
class var sharedInstance: Singleton {
if (!Static.instance != nil) {
Static.instance = Singleton()
}
return Static.instance!
}
private init() {
print("initialised first time")
}
}
Thanks.
as I know in swift init
get called automatically when you initialize a class like the Kotlin
in case of java you need to call the init method from the class constructor
like this
public class Singleton {
private static Singleton INSTANCE = null;
private Singleton() {
init();
}
public static Singleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
return(INSTANCE);
}
private void init() {
Log.d(TAG, "is this firing");
}
}
You did not call the init method during instance creation. Do this:
public class Singleton {
private static Singleton INSTANCE = null;
private Singleton() {
init();
}
public static Singleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
return(INSTANCE);
}
private void init() {
Log.d(TAG, "is this firing");
}
}
init()
is a function that you have defined only but haven't invoked from anywhere else.
invoke init() from inside your private constructor where init gets called only once
when your singleton object gets created for the first time:
private Singleton() {
init();
}
if you wish to call it every time
, put init() function inside getInstance()
:
public static Singleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
init();
return(INSTANCE);
}
Check your LogCat window now.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.