Home > front end >  Wi-Fi Connection check using singleton class android studio
Wi-Fi Connection check using singleton class android studio

Time:06-08

I was doing Wi-Fi connection using singleton class, when button press then error message show Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference

Singleton Class

public class WifiConnectivity {

    private static WifiConnectivity INSTANCE = null ;
    private ConnectivityManager cnmgr;
    Context context;
    int ipadress;
    String ipAddress;


    public static WifiConnectivity getInstance() {
        if (INSTANCE == null){
            INSTANCE = new WifiConnectivity();
        }
        return INSTANCE;
    }

    public ConnectivityManager getWifiConnectivty(int ipadress , String ipAddress){
        this.ipadress = ipadress;
        this.ipAddress = ipAddress;
        return cnmgr;
    }

    public void Connectivity() {
        cnmgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cnmgr.getActiveNetworkInfo() != null && cnmgr.getActiveNetworkInfo().isAvailable()
                && cnmgr.getActiveNetworkInfo().isConnected()) {
            WifiManager wifiMgr = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
            ipadress = wifiInfo.getIpAddress();
            ipAddress = Formatter.formatIpAddress(ipadress);
            Log.d(TAG, "wifi_connectivity:");
        }else {
            Toast.makeText(context , "Wifi Not Connect" , Toast.LENGTH_SHORT).show();
          
        }

    }
    private WifiConnectivity(){}
}

Singleton instance used when button pressed

WifiConnectivity.getInstance().getWifiConnectivty(ipadress, ipAddress);WifiConnectivity.getInstance().Connectivity();

CodePudding user response:

That means Context is null and that is because any reference has never been assigned to it.

On the other hand, be very careful with assigning Activity or Fragment context references in static classes. You will have memory leaks as soon as Android tries to delete fragments or activities.

IMHO, you shouldn't need to create a static class for that feature.

CodePudding user response:

You dont have to create instance variable of context in static class instead you can directly pass context of the activity or fragment from where the connectivity method is called.

WifiConnectivity.getInstance().Connectivity(context);
  • Related