Here is my singleton class with weak reference.
public class HandheldMapViewProvider {
private static WeakReference<HandheldMapViewProvider> mInstance = null;
private HandheldMapViewProvider(){
}
public static synchronized WeakReference<HandheldMapViewProvider> getInstance(){
if(mInstance == null){
mInstance = new WeakReference<HandheldMapViewProvider>(new HandheldMapViewProvider());
}
return mInstance;
}
public void onprint(String data){
Log.D("TAG",data)
}
}
Usage of above class is as follow.
private WeakReference<HandheldMapViewProvider> hereMapViewProvider;
public void onprint(){
hereMapViewProvider = HandheldMapViewProvider.getInstance();
hereMapViewProvider.get().onprint("somevalue");
}
While calling onprint method first time app get crash sometimes due to get() is null.
Any idea where i am doing it wrong. its not happening all time.
Solution is as below.
public static synchronized HandheldMapViewProvider getInstance(){
HandheldMapViewProvider mapProvider = mInstance == null ? null :mInstance.get();
if(mapProvider == null){
mInstance = new WeakReference<HandheldMapViewProvider>(mapProvider =new HandheldMapViewProvider());
}
return mapProvider;
}