Search code examples
javaandroidservicesystemandroid-context

Passing context from MainActivity to other Class for System services


I want to clean my Main activity class a bit and transfer some code to other class to make my code a bit more easier to read. I got a situation like this

MainActivity Class

public class MainActivity extends AppCompatActivity { 
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        getData("2B1A4D3C");
     }
    public void getData(String Hex) {
        Static staticClass = new Static();
           if (staticClass.isNetworkAvailable(MainActivity.this) == true) {
                  staticClass.setData(response);
           }
    }
}

2nd class

class Static extends AppCompatActivity {
    public boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) 
            getSystemService(context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = 
            connectivityManager.getActiveNetworkInfo();
    if ( activeNetworkInfo != null ) {
        return true;
    } else {
        return false;
    }
}

When I pass contex like this -> isNetworkAvailable(MainActivity.this) I got a crash. And get an error

System services not available to Activities before onCreate()

What is a proper way to pass context?


Solution

  • You need to use:

        ConnectivityManager connectivityManager = (ConnectivityManager) 
            context.getSystemService(context.CONNECTIVITY_SERVICE);
    

    Otherwise that call will actually be Static.this.getSystemService(...) and since the Static instance was created by you and not the system, it isn't a valid Context.

    But in this case, I don't see any reason for the Static class to extend AppCompatActivity so you should probably remove that.