Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot make a static reference to the non-static method getSystemService(String) from the type

I have this function which network connection

public boolean isNetworkConnected() {
    ConnectivityManager conManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
   NetworkInfo netInfo = conManager.getActiveNetworkInfo();

   if (netInfo == null) {
       // There are no active networks.
       return false;
   } else {
       return true;
   }
}

But when i a trying to make it static so that i can use it in every activity it is throwing:

Cannot make a static reference to the non-static method getSystemService(String) from the type

I don't want to create the object of the class every time .

like image 626
Developer Avatar asked Aug 01 '13 11:08

Developer


People also ask

How do you create a static reference from a non-static method?

i.e. referring a variable using static reference implies to referring using the class name. But, to access instance variables it is a must to create an object, these are not available in the memory, before instantiation. Therefore, you cannot make static reference to non-static fields(variables) in Java.

What is a static reference in Java?

Static Method Static methods are the methods in Java that can be called without creating an object of class. They are referenced by the class name itself or reference to the Object of that class.


1 Answers

Add the non-static dependencies as parameters:

public static boolean isNetworkConnected(Context c) {
      ConnectivityManager conManager = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
      NetworkInfo netInfo = conManager.getActiveNetworkInfo();
      return ( netInfo != null && netInfo.isConnected() );
}
like image 121
S.D. Avatar answered Sep 19 '22 23:09

S.D.