In my application I need to know the name of package name. I have no problem when I want to grab it in activities but i can't take it in other classes. Following code is working in activity but i don't know why it has problem in simple class.
String packageName = getPackageName();
In my class I tried to write this code:
Context context = getApplicationContext();
String packageName = context.getPackageName();
but compiler said getApplicationContext()
method is undefined for this class.
How can I take package name within this class?
Use following
The simple, or another way is to pass Context into the helper class constructor:
If you use gradle build, use this:
BuildConfig.APPLICATION_ID
to get the package name of the application.getApplicationContext() is a method of ContextWrapper ( super class of Activity).
If you want to use it in your classes you will have to pass a reference of a Context or its subclass and then use it
http://developer.android.com/reference/android/content/ContextWrapper.html#getPackageName()
Simplest answer is make a class name constructor and pass the ApplicationContext in that constructor -
Using instance of the class you can get package name by using
getClass().getPackage().getName()
to the instanceSample Code