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;
}
}
您可以在活动中使用此简单代码获取包名称
如果你没有参加活动,那么你可以使用
在片段中,你可以使用这个