What is the correct way to call a method from a class that inherits from an activity?

0

Because if I instantiate the class with "new" and call the same method as Java does not work. I have a class that inherits from an activity and I needed to use its method in several classes. Does anyone know how to do this? Thank you in advance.

    
asked by anonymous 22.10.2015 / 16:33

2 answers

1

No class that inherits from Activity should / can be instantiated with "new".

  

An Activity is an application component that provides a screen with which users can interact in order to do something. [Learn more]

They are managed internally by the Android Activity framework which, among other things, manages its lifecycle. So it has to be created using the mechanism that the framework provides for it.

An Activity will need to be launched using a Intent which describes the Activity that you want to start. The Intent specifies the Activity that you want to start, or describes the type of action you want to perform. [Read about]

If an Activity needs to access methods of another Activity then your application is poorly structured.

There are several ways to avoid this need.
They will depend on what you intend to do, so you will need to be more specific in your question.

    
22.10.2015 / 17:28
1

You can create an Utils class, for example. In this class you create a method to check the connection. You will probably need a Context object to do the verification. You may receive Context as the method parameter. For example:

public static boolean checkConnection(Context context) {
    ConnectivityManager cm =
        (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();
}

In your activities you can call:

Utils.checkConnection(this)

Part of this code has been extracted from this answer here

    
23.10.2015 / 16:10