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

Asked

Viewed 444 times

0

Because if I instantiate the class with "new" and call the method equal to Java it doesn’t work. I have a class that inherits from an Activity and I needed to use her method in several classes. Does anyone know how to do that? I thank you in advance.

  • You need to give a better study in the life cycle of Android and especially in design Patterns, with this you will find the answers to your questions, but already one of the solutions advancing is you use the standard Singleton.

2 answers

2

No class I inherit from Activity should/can be instantiated with "new".

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

They are managed internally by Android Activity framework which, among other things, manages its life cycle. Therefore, it will have to be created using the mechanism that framework available for this.

One Activity shall be launched using a Intent that describes the Activity you want to start. Intent specifies the Activity that you want to start or describe the type of action you want to perform.

If a Activity needs to access another’s methods Activity then its 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.

  • I am using a method to check if there is connection on my device, for this I need to use an Activity. Since I’m going to use this method five times, I didn’t want to have to replicate the code.

  • 1

    Why that method has to be in an Activity?

2

You can create a Utils class, for example. In this class you create a method to verify the connection. You probably need a Context object to check. You can receive Context as a 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 that code was extracted from that reply here

Browser other questions tagged

You are not signed in. Login or sign up in order to post.