0

I've build a singleton class to check if I am online before performing an external database upload.

To do so, this is the class:

public class InternetConnection
{
    private static InternetConnection instance = null;

    public static InternetConnection getInstance()
    {
        if(instance == null)
        {
            instance = new InternetConnection();
        }

        return instance;
    }


    private InternetConnection()
    {

    }

    public boolean isOnline(Context context)
    {

        ConnectivityManager connMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        return (networkInfo != null && networkInfo.isConnected());

    }
}

Outside, on an Activity, I call it like so:

if (InternetConnection.getInstance().isOnline(this)) {
  //I am online, so I upload to my external database
} else {
  // I am not online
}

However, when it enters in getInstance() method, it evaluates instance == null ( which when I debug is true ) but, instead of entering in true branch and performing instance = new InternetConnection() it skips this branck and returns null, which causes a null object exception outside.

Why is this happening? How is possible that if instance == null is true it skips the branch for true case?

Thanks!

kaxi1993
  • 4,535
  • 4
  • 29
  • 47
Toni
  • 165
  • 1
  • 13

0 Answers0