I'm new to android programming. I've created an app using Eclipse with a MainActivity.java and ClassFragment.java files. ClassFragment is a frangment. And I'm using newly updated appcompat library. I just want to implement a toast in my fragment with will show the version vode and version name of the app. I've used the following code
PackageManager pInfo = getActivity().getPackageManager.getPackageInfo(getActivity().getPackageName, 0);
But its showing java compilation error PackageManager namenotfoundexception. Pls help me out from this. Thanks in advance.
Asked
Active
Viewed 9,664 times
10

yAnTar
- 4,269
- 9
- 47
- 73

user5770725
- 101
- 1
- 3
3 Answers
20
There is one behaviour change in Android API level 30 because of which we get NameNotFoundException when we call getPackageInfo on Android 11 even if the app/package app is installed on user's device. From Android API 30, we need to specify the package name in manifest in order to check if that package is installed on user's device.
<?xml version="1.0" encoding="utf-8"?>
<manifest
...>
<queries>
<package android:name="com.example.Maps" />
</queries>
<application
android:name=".Notes App"
.../>
</manifest>

Ken
- 1,691
- 5
- 22
- 38

Ramakrishna Joshi
- 1,442
- 17
- 22
-
Reference link to the behavior change would be great, @ramakrishna-joshi – Ken Jan 21 '22 at 19:28
-
1@Ken Here is the official documentation link : https://developer.android.com/training/package-visibility – Ramakrishna Joshi Feb 04 '22 at 22:14
1
PackageManager manager = getActivity().getPackageManager();
PackageInfo info;
try {
info = manager.getPackageInfo(getActivity().getPackageName(), 0);
String strVersion = "Version: " + info.versionName;
String strVersionCode = " Build: "+ info.versionCode);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Htoo Aung Hlaing
- 2,173
- 15
- 26
-
Anyone have a clue why the error is showing up in the first place if the version name actually exists? – Saamer Sep 09 '19 at 07:33
-
@Htoo The logcat does show a name not found exception, but the name actually does exist. That's why my question was asking why the exception get raised even though the version name does exist – Saamer Sep 09 '19 at 14:50
-
1@Saamer You had an error in the method call getActivity().getPackageName. It was necessary so getActivity().getPackageName(). – Dmitriy Sep 13 '21 at 15:52
-
I don’t remember what project I was working on that was so long ago. But thank you ! – Saamer Sep 14 '21 at 05:40
0
Since Android API level 30 you need to add this permission android.permission.QUERY_ALL_PACKAGES
more info: https://developer.android.com/training/package-visibility

M_rey3000
- 176
- 3
- 14