Get application context from non activity singleton class

Update: 06-Mar-18 Use MyApplication instance instead of Context instance. Application instance is a singleton context instance itself. public class MyApplication extends Application { private static MyApplication mContext; @Override public void onCreate() { super.onCreate(); mContext = this; } public static MyApplication getContext() { return mContext; } } Previous Answer You can get the the application context … Read more

Dagger 2 injecting Android Application Context

@Module public class MainActivityModule { private final Context context; public MainActivityModule (Context context) { this.context = context; } @Provides //scope is not necessary for parameters stored within the module public Context context() { return context; } } @Component(modules={MainActivityModule.class}) @Singleton public interface MainActivityComponent { Context context(); void inject(MainActivity mainActivity); } And then MainActivityComponent mainActivityComponent = DaggerMainActivityComponent.builder() … Read more

Call getLayoutInflater() in places not in activity

You can use this outside activities – all you need is to provide a Context: LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE ); Then to retrieve your different widgets, you inflate a layout: View view = inflater.inflate( R.layout.myNewInflatedLayout, null ); Button myButton = (Button) view.findViewById( R.id.myButton ); EDIT as of July 2014 Davide’s answer on how … Read more

Why getApplicationContext() in constructor of Activity throws null pointer exception?

Just to get a feeling of what’s going on. Activity extends ContextThemeWrapper which extends ContextWrapper from whom Activity inherits getApplicationContext(). ContextWrapper implements it as : @Override public Context getApplicationContext() { return mBase.getApplicationContext(); // mBase is a Context } The only public constructor of ContextWrapper is : public ContextWrapper(Context base) { mBase = base; } in … Read more

get Context in non-Activity class [duplicate]

If your class is non-activity class, and creating an instance of it from the activiy, you can pass an instance of context via constructor of the later as follows: class YourNonActivityClass{ // variable to hold context private Context context; //save the context recievied via constructor in a local variable public YourNonActivityClass(Context context){ this.context=context; } } … Read more

Why does AlertDialog.Builder(Context context) only accepts Activity as a parameter?

An Activity inherits a Context. AlertDialog.Builder specifies a Context argument because it can then be used by ANY class that is a subclass of Context, including an Activity, ListActivity, Service, … (There is a common coding idiom behind this – you can learn more about it by reading Item I8 (on Interfaces and Abstract classes) … Read more