Home » Android » Can't find getPackageManager() method in android

Can't find getPackageManager() method in android

Posted by: admin April 23, 2020 Leave a comment


I have problem with my project.

I can’t find getPackageManager() method although i imported android.content.pm.PackageManager;

what wrong with this piece of code

List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);

.Thanks for your helping

How to&Answers:

The error is not in your line of code, but where you are calling it. getPackageManager() is a method of Context. You can use this method inside an Activity (because an Activity is a Context), but if you are calling it elsewhere, you need to pass a Context. In a fragment you may also have access to the getActivity() function, which returns the Acitivity-Context.

    Context context...;



If you are using it in Activity you will not get an error or warning for getPacketManager, but if you are using it in Fragments you should prefix it with getActivity.


PackageManager pm = getActivity().getPackageManager();


Try this..

I guess you are extends is Fragment

So, you have to use getActivity().getPackageManager() like below

List<PackageInfo> packs = getActivity().getPackageManager().getInstalledPackages(0);

Or extends is BroadcastReceiver

In side onReceive you have to use context.getPackageManager() like below

List<PackageInfo> packs = context.getPackageManager().getInstalledPackages(0);


I think this may be due to Context

If you are using

Activity : Then you can directly access this method by importing android.content.pm.PackageManager;

If you are using Fragment : Then you need to provide getActivity() to avail method


List<PackageInfo> packs = getActivity().getPackageManager().getInstalledPackages(0);


you can also try context.getPackageManager() if you have context passed as a parameter in your class constructor eg for Broadcast receiver


if you extends fragment use getActivity().getPackageManager().getInstalledPackages(0);
else context.getPackageManager().getInstalledPackages(0);