-1

I am trying to get the package name of the app using the below code in my adapter java file. But I am getting nullpointer exception.

Fatal Exception: java.lang.NullPointerException
Attempt to invoke virtual method 'android.content.pm.PackageManager android.content.Context.getPackageManager()' on a null object reference

Code:

private static boolean appsPackageName() {
        PackageInfo pInfo;
        try {
            pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);;
        } catch (PackageManager.NameNotFoundException e) {
            throw new RuntimeException("Could not get package name: " + e);
        }

        if (pInfo.packageName.equals("com.app.sample")) {
            return true;
        } else {
            return  false;
        }
    }
sejn
  • 2,040
  • 6
  • 28
  • 82
  • Does this answer your question? [How to get package name from anywhere?](https://stackoverflow.com/questions/6589797/how-to-get-package-name-from-anywhere) – Sercan Jul 28 '22 at 16:51
  • No, BuidConfig.ApplicationId not returning the package name of the app – sejn Jul 28 '22 at 17:07
  • are you **really sure** the `context` is non-null before invoking the static method? If you can, consider refactoring the method signature to `appsPackageName(Context context)` so that you can be absolutely sure you pass in a non-null context from wherever you're calling this method. – Shark Jul 28 '22 at 17:11
  • Yes I have context as well. – sejn Jul 28 '22 at 17:35

1 Answers1

0

You can get package name by using this simple code in your activity

getApplicationContext().getPackageName()

if you are not in activity then you can use

context.getApplicationContext().getPackageName()

In Fragment you can use this

requireActivity.getApplicationContext().getPackageName()