Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: It is a good practice to get Context statically? [duplicate]

Tags:

android

currently, in my App I have the following class:

public class MyApp extends Application {

    private static Context context;

    public void onCreate(){
        super.onCreate();
        MyApp.context = getApplicationContext();
    }

    public static Context getContext() {
        return MyApp.context;
    }
}

I use this to have Context in classes that are neither Activities nor Fragment. It's there any difference between use the context stored on this class and use and activity as context? It is a good practice to have this class or should I provide an activity as context to any class who needs it?

Thanks.

like image 638
mario595 Avatar asked Jan 24 '14 14:01

mario595


People also ask

Do not place Android context classes in static fields This is a memory leak?

The solution itself is fairly simple: Do not place context fields in static instances, whether that of a wrapping class or declaring it static directly. And the solution to the warning is simple: don't place the field statically. In your case, pass the context as an instance to the method.

What should I pass in context android?

It is used to return the Context which is linked to the Application which holds all activities running inside it. When we call a method or a constructor, we often have to pass a Context and often we use “this” to pass the activity Context or “getApplicationContext” to pass the application Context.

What is Android content context?

Definition. it's the context of current state of the application/object. It lets newly-created objects understand what has been going on. Typically, you call it to get information regarding another part of your program (activity and package/application).

How many types of context are there in Android?

There are essentially two types of context : Application Context. Activity Context.


1 Answers

It's there any difference between use the context stored on this class and use and activity as context?

Yes. Please read Dave Smith's epic blog post on the subject. In summary: only use an Application when you know why Application is the right answer... and it rarely is.

It is a good practice to have this class

IMHO, not usually. You may sometimes need an Application object, but you do not need your own custom subclass, and you do not need to make it a singleton.

should I provide an activity as context to any class who needs it?

You supply the right Context instance to any method that needs it. As Dave Smith describes in that blog post, not all Context instances are created equal. Only use Application when Application is the right sort of Context.

like image 192
CommonsWare Avatar answered Nov 15 '22 20:11

CommonsWare