user3418401
user3418401

Reputation: 417

Can't find getPackageManager() method in android

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

Upvotes: 40

Views: 84635

Answers (7)

simpleuser
simpleuser

Reputation: 1682

If using Jetpack Compose with Kotlin, use LocalContext.current.packageManager

Upvotes: 0

Shashank Pujari
Shashank Pujari

Reputation: 199

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.

example:

PackageManager pm = getActivity().getPackageManager();

Upvotes: 13

NameSpace
NameSpace

Reputation: 10177

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...;

    context.getPackageManager();
    getActivity().getPackageManager();

Upvotes: 81

Ronak Mehta
Ronak Mehta

Reputation: 5979

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

I.E.

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

Upvotes: 4

Hariharan
Hariharan

Reputation: 24853

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);

Upvotes: 5

Ashwin S Ashok
Ashwin S Ashok

Reputation: 3663

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

Upvotes: 1

ARK
ARK

Reputation: 173

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

Upvotes: 2

Related Questions